Springboot快速上手- 第七篇 单元测试
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 常见的第一种方式
@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)
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等等
继续学习吧~~哈哈,我给大家来了硬广,cc老师创立的私塾在线现在推出2020年高级架构师课程培训课程现在折扣才6800元,包含300+录,60+直播,面试技巧等课程内容,惊喜多多!详情都在私塾的官网,感兴趣的小伙伴,可以一起去 【****** 】 学习