Skip to main content
 首页 » 编程设计

spring-boot之将 MockMvc 与 SpringBootTest 结合使用和使用 WebMvcTest 之间的区别

2024年02月27日21Leo_wl

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

请您参考如下方法:

@SpringBootTest 是通用的测试注解。如果您正在寻找在 1.4 之前执行相同操作的工具,那么您应该使用它。它根本不使用切片,这意味着它将启动完整的应用程序上下文,并且根本不自定义组件扫描。

@WebMvcTest 只会扫描您定义的 Controller 和 MVC 基础结构。就是这样。因此,如果您的 Controller 对服务层中的其他 bean 有一定的依赖性,则在您自己加载该配置或为其提供模拟之前,测试不会开始。这要快得多,因为我们只加载应用程序的一小部分。该注释使用了切片。

Reading the doc也许也应该对你有帮助。