首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >结合使用MockMvc和SpringBootTest与使用WebMvcTest的区别

结合使用MockMvc和SpringBootTest与使用WebMvcTest的区别
EN

Stack Overflow用户
提问于 2016-10-05 12:44:57
回答 1查看 50.4K关注 0票数 117

我是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!")));
    }
}

这个测试使用了@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有什么不同呢?这有什么不同之处?

编辑:添加代码片段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!"));
    }
}
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39865596

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档