Spring Boot @WebMvcTest 与 @SpringBootTest

bel*_*ros 6 java spring-test-mvc spring-boot

我有一个简单的健康控制器定义如下:

@RestController
@RequestMapping("/admin")
public class AdminController {

    @Value("${spring.application.name}")
    String serviceName;

    @GetMapping("/health")
    String getHealth() {
        return serviceName + " up and running";
    }
}
Run Code Online (Sandbox Code Playgroud)

以及测试它的测试类:

@WebMvcTest(RedisController.class)
class AdminControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void healthShouldReturnDefaultMessage() throws Exception {
        this.mockMvc.perform(get("/admin/health"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("live-data-service up and running")));
    }
}
Run Code Online (Sandbox Code Playgroud)

运行测试时,我收到以下错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field configuration in com.XXXX.LiveDataServiceApplication required a bean of type 'com.XXXXX.AppConfiguration' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.XXXX.AppConfiguration' in your configuration.
Run Code Online (Sandbox Code Playgroud)

这里是AppConfiguration.java在与主 spring boot 应用程序类相同的包中定义的:

@WebMvcTest(RedisController.class)
class AdminControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void healthShouldReturnDefaultMessage() throws Exception {
        this.mockMvc.perform(get("/admin/health"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("live-data-service up and running")));
    }
}
Run Code Online (Sandbox Code Playgroud)

主要类别:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field configuration in com.XXXX.LiveDataServiceApplication required a bean of type 'com.XXXXX.AppConfiguration' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Action:

Consider defining a bean of type 'com.XXXX.AppConfiguration' in your configuration.
Run Code Online (Sandbox Code Playgroud)

如果我将测试类中的注释修改如下,则测试通过:

@Configuration
@EnableConfigurationProperties
@ConfigurationProperties
public class AppConfiguration {

    @Value("${redis.host}")
    private String redisHost;

    @Value("${redis.port}")
    private int redisPort;

    @Value("${redis.password:}")
    private String redisPassword;
...
// getters and setters come here
Run Code Online (Sandbox Code Playgroud)

我缺少什么?

Dea*_*ool 7

@WebMvcTest您应该了解和的用法@SpringBootTest

@WebMvcTest :注释只是实例化Web层而不是整个上下文,因此控制器类中的所有依赖项都应该被模拟,你可以查看文档

Spring Boot 仅实例化 Web 层而不是整个上下文。在具有多个控制器的应用程序中,您甚至可以要求仅实例化一个控制器,例如,@WebMvcTest(HomeController.class).

我们使用 @MockBean 为 GreetingService 创建并注入模拟(如果不这样做,应用程序上下文将无法启动)

SpringBootTest : Spring boot测试注释实际加载测试环境的应用程序上下文

@SpringBootTest 注释告诉 Spring Boot 查找主配置类(例如带有 @SpringBootApplication 的配置类)并使用它来启动 Spring 应用程序上下文。


小智 0

定义 src/test/resource/application.file 示例中的所有属性,以将 junit 5 用于其余层:

@ExtendWith(MockitoExtension.class)
public class RestTest {

    
    @InjectMocks
    private RestClass  restClass;
    
    
    
    private MockMvc mockMvc;
    
    @BeforeEach
    public void init() throws Exception {
        MockitoAnnotations.initMocks(this);
        mockMvc = MockMvcBuilders.standaloneSetup(restClass).build();
    }
    
    @Test
    public void test() throws Exception {
        String url = "/url";
        ResultActions resultActions = mockMvc.perform(get(url));
        resultActions.andExpect(status().isOk());

    }
    }
Run Code Online (Sandbox Code Playgroud)