我是Spring Boot的新手,我正在尝试了解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!")));
}
}
Run Code Online (Sandbox Code Playgroud)
此测试使用@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!")));
}
}
Run Code Online (Sandbox Code Playgroud)
此测试使用@SpringBootTest注释和MockMvc.那么这与代码片段1有何不同?这有什么不同的做法?
编辑:添加代码片段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 …
Run Code Online (Sandbox Code Playgroud) spring-boot ×1