【发布时间】:2017-02-13 09:42:27
【问题描述】:
我是 Spring Boot 新手,正在尝试了解 SpringBoot 中的测试工作原理。我对以下两个代码sn-ps有什么区别感到有些困惑:
代码 sn-p 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 层。
代码 sn-p 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。那么这与代码 sn-p 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 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!"));
}
}
【问题讨论】:
标签: spring-boot