【问题标题】:Spring Boot unit test constructor injectionSpring Boot 单元测试构造函数注入
【发布时间】:2020-10-30 09:14:31
【问题描述】:

我正在使用 Spring Boot 创建一个 REST API 并在我的控制器上编写一些单元测试。 我知道在spring中注入bean的推荐方式是构造函数注入。 但是当我将@SpringBootTest 注释添加到我的测试类时,我无法用构造函数注入我的控制器类,我发现自己不得不使用@Autowired

有一些解释,是否有另一种方法可以通过SpringBootTest 使用构造函数注入。

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class PersonControllerTest {

    @LocalServerPort
    private int port;

    @Autowired
    private PersonController controller;

    @Autowired
    private TestRestTemplate restTemplate;


    @Test
    public void greetingShouldReturnDefaultMessage() throws Exception {
        assertThat(this.restTemplate.getForObject("http://localhost:" + port + "/cvtech/Persons/",
                                                  String.class)).contains("content");
    }

    @Test
    public void contextLoads() throws Exception {
        assertThat(controller).isNotNull();
    }
    @Test
    void findAllByJob() {
    }
}

【问题讨论】:

  • 你不希望 Spring 和 DI 用于单元测试。将其用于集成测试。如果是集成测试,我建议你看看 MockMVC
  • 谢谢,但我认为 SpringBootTest 两者都做。

标签: java spring spring-boot junit5


【解决方案1】:

您的测试可以使用字段注入,因为测试本身不属于您的域;测试不会成为您的应用程序上下文的一部分。

还有

您不想使用SpringBootTest 来测试控制器,因为这将连接所有可能过于繁重且耗时的bean。相反,您可能只想创建控制器及其依赖项。

所以你最好的选择是使用@WebMvcTest,它只会创建测试指定控制器所需的bean。

@ExtendWith(SpringExtension.class)
@WebMvcTest(controllers = PersonController.class)
class PersonControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    public void greetingShouldReturnDefaultMessage() throws Exception {
        mockMvc.perform(get("/cvtech/Persons"))
               .andExpect(status().isOk())
               .andExpect(content().string(contains("content")));
    }
}

请注意,@WebMvcTest 将搜索带有 @SpringBootConfiguration 注释的类,因为它是默认配置。如果没有找到,或者你想手动指定一些配置类,也可以用@ContextConfiguration注解测试。

另外,作为旁注,当使用TestRestTemplate 时,您不需要指定主机和端口。只需致电restTemplate.getForObject("/cvtech/persons", String.class)); 使用MockMvcWebTestClient 时相同。

【讨论】:

    猜你喜欢
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多