在 SpringBootTest 中使用 MockMvc 与使用 WebMvcTest 的区别

我是 SpringBoot 的新手,正在尝试理解 SpringBoot 中测试是如何工作的。我对下面两个代码片段之间的区别有点困惑:

代码段1:

@RunWith(SpringRunner.class)
@WebMvcTest(HelloController.class)
public class HelloControllerApplicationTest {
@Autowired
private MockMvc mvc;


@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
}
}

这个测试使用了 @WebMvcTest注释,我相信这是用于特性片测试,并且只测试 Web 应用程序的 MVC 层。

代码段2:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {


@Autowired
private MockMvc mvc;


@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Greetings from Spring Boot!")));
}
}

这个测试使用 @SpringBootTest注释和 MockMvc。那么这与代码片段1有什么不同呢?这有什么不同吗?

编辑: 添加 CodeSnippet 3(在 Spring 文档中发现这是一个集成测试示例)

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {
    

@LocalServerPort private int port;
private URL base;
    

@Autowired private TestRestTemplate template;
    

@Before public void setUp() throws Exception {
this.base = new URL("http://localhost:" + port + "/");
}
    

@Test public void getHello() throws Exception {
ResponseEntity < String > response = template.getForEntity(base.toString(), String.class);
assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
}
}
66655 次浏览

@SpringBootTest是通用的测试注释。如果你在寻找在1.4之前做同样事情的东西,那就是你应该使用的东西。它根本不使用 切片,这意味着它将启动完整的应用程序上下文,并且根本不定制组件扫描。

@WebMvcTest只会扫描您定义的控制器和 MVC 基础设施。就是这样。因此,如果您的控制器对服务层中的其他 bean 具有某种依赖性,那么在您自己加载该配置或为其提供模拟之前,测试不会启动。这是快得多,因为我们只加载了你的应用程序的一小部分。此注释使用切片。

阅读文档 可能也会对你有所帮助。

@ SpringBootTest 注释告诉 Spring Boot 去寻找一个主配置类(例如@SpringBootApplication) ,并使用它来启动 Spring 应用程序上下文。SpringBootTest 加载完整的应用程序并注入所有可能比较慢的 bean。

@ WebMvcTest -用于测试控制器层,您需要使用 Mock Objects 提供所需的其余依赖项。

下面还有一些注释供您参考。

测试应用程序的片 有时候,您希望测试应用程序的一个简单“片”,而不是自动配置整个应用程序。Spring Boot 1.4引入了4个新的测试注释:

@WebMvcTest - for testing the controller layer
@JsonTest - for testing the JSON marshalling and unmarshalling
@DataJpaTest - for testing the repository layer
@RestClientTests - for testing REST clients

更多信息请参考: https://spring.io/guides/gs/testing-web/