码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot集成测试

时间:2020-01-10 00:25:26      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:servlet   boot   service   注意   window   blank   image   figure   注解   

一. 测试一般程序(Service/DAO/Util类)

1. 在pom.xml中引入依赖

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

<1> 如果使用IntelliJ IDEA,可以使用快捷键直接生成:

  • Windows快捷键:Ctrl + Shift + T
  • Mac快捷键:Commond + Shift + T

<2> 自己手动去创建

技术图片

 

 

 

3. 编写测试类

<1> 在测试类上加入@RunWith(SpringRunner.class) 与@SpringBootTest 注解,
<2> 编写测试方法并添加@Test注解

技术图片

 

 

 

二. 测试Controller类

1. 使用TestRestTemplate对象测试

<1> 在pom.xml中引入依赖(与上相同)
<2> 在测试类上加入@RunWith(SpringRunner.class) 与 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 注解
<3> 使用TestRestTemplate对象测试

 技术图片

 技术图片

2. 使用@WebMvcTest 注解测试

<1> 在pom.xml中引入依赖(与上相同)
<2> 在测试类上加入@RunWith(SpringRunner.class) 与 @WebMvcTest 注解
<3> 使用MockMvc对象测试

仍然测试UserController类

技术图片

使用总结及相关注意点

1. @WebMvcTest 与 @SpringBootTest 注解不能一起使用,会报错

错误信息:found multiple declarations of @BootstrapWith
一个是:(value=class org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTestContextBootstrapper)
一个是:(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)

技术图片

 

2. 使用@WebMvcTest注解进行测试时,只会加载在@WebMvcTest()中配置的bean,而@SpringBootTest注解会加载所有被Spring容器管理的bean

例如:@WebMvcTest(UserController.class) 只会加载UserController类

3. 如果使用MockMvc对象时,又希望会加载所有被Spring容器管理的bean,可以使用@AutoConfigureMockMvc注解

技术图片

 

 

本文转自:https://www.jianshu.com/p/3a82791b9d3e?from=singlemessage

 

SpringBoot集成测试

标签:servlet   boot   service   注意   window   blank   image   figure   注解   

原文地址:https://www.cnblogs.com/nizuimeiabc1/p/12173927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!