欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Springboot快速上手- 第七篇 单元测试

程序员文章站 2022-06-16 22:19:29
...

1 概述

SpringBoot对测试提供了一些简化支持,只需要添加起步依赖即可使用:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2 以前的测试方式

SpringJUnit支持,由此引入Spring-Test框架支持,通过这个注解让SpringJUnit4ClassRunner这个类提供Spring测试上下文
@RunWith(SpringJUnit4ClassRunner.class)
指定SpringBoot工程的Application启动类,通过这个注解加载和配置Spring应用上下文
@SpringApplicationConfiguration(classes = App.class)
由于是Web项目,Junit需要模拟ServletContext,因此需要给测试类加上@WebAppConfiguration
@WebAppConfiguration

3 常见的第一种方式

Springboot快速上手- 第七篇 单元测试
            
    
    博客分类: javaspringboot
image.png

@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
@AutoConfigureMockMvc
这种方式下:直接
@Autowired
private MockMvc mockMvc;
然后就可以使用mockMvc
1:@RunWith里面,不再是SpringJUnit4ClassRunner.class,而是springboot专门做的一个启动类SpringRunner.class,当然,也可以使用@RunWith(SpringJUnit4ClassRunner.class)
2:也不使用@SpringApplicationConfiguration了,使用@SpringBootTest来指定启动类,启动类上面就有配置的注解
3:还可以指定随机的端口
@SpringBootTest(classes = App.class,webEnvironment = WebEnvironment.RANDOM_PORT)
4:可以引入自定义的配置类
@Import(MyTestsConfiguration.class)

 

Springboot快速上手- 第七篇 单元测试
            
    
    博客分类: javaspringboot
image.png

4 常见的第二种方式

1:如果没有 @AutoConfigureMockMvc, 那么就需要
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
2:然后加上:

@Before
public void setup() {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}

然后就可以使用mockMvc

5 常见的第三种方式:使用TestRestTemplate

@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class,webEnvironment = WebEnvironment.RANDOM_PORT)
直接注入:
@Autowired
private TestRestTemplate rest;

然后就可以直接使用TestRestTemplate了

6 其它

Springboot还有一些专项的检查,比如:@DataJpaTest、@JdbcTest、@DataMongoTest、@RestClientTest、@JsonTest等等