没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
springboot使用单元测试实战使用单元测试实战
主要介绍了springboot使用单元测试实战,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随
小编过来看看吧
前言前言
springboot提供了 spirng-boot-starter-test 以供开发者使用单元测试,在引入 spring-boot-starter-test 依赖后:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
其中包含以下几个库:
Junit ——常用的单元测试库
Spring Test & Spring Boot Test ——对Spring应用的集成测试支持
AssertJ——一个断言库
Hamcrest—— 一个匹配对象的库
Mockito—— 一个Java模拟框架
JSONassert—— 一个针对JSON的断言库
JsonPath—— 用于JSON的XPath
下面我们将从Service层和Controller层的角度来简单介绍下单元测试
Service单元测试单元测试
在SpringBoot 2.0中,创建一个Service的单元测试,代码如下:
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceImplTest {
@Autowired
private UserService userService;
@Test
public void insertUser() {
User user = new User();
user.setUsername("li ning");
user.setPassword("123456");
userService.insertUser(user);
}
}
上面的测试非常简单,主要需要注意两个注解: @RunWith 和 @SpringBootTest
1. @RunWith : 该注解标签是Junit提供的,用来说明此测试类的运行者,这里用了 SpringRunner ,它实际上继承了
SpringJUnit4ClassRunner 类,而 SpringJUnit4ClassRunner 这个类是一个针对Junit 运行环境的自定义扩展,用来标准
化在Springboot环境下Junit4.x的测试用例
2. @SpringBootTest 为 springApplication创建上下文并支持SpringBoot特性
使用 @SpringBootTest 的 webEnvironment 属性定义运行环境:
1. Mock(默认) : 加载WebApplicationContext 并提供模拟的web环境 Servlet环境,使用此批注时,不会启动嵌入式服务器
2. RANDOM_PORT : 加载WebServerApplicationContext 并提供真实的web环境,嵌入式服务器, 监听端口是随机的
3. DEFINED_PORT : 加载WebServerApplicationContext并提供真实的Web环境,嵌入式服务器启动并监听定义的端口(来
自 application.properties或默认端口 8080)
4. NONE : 使用SpringApplication加载ApplicationContext 但不提供任何Web环境
Controller的单元测试的单元测试
首先创建一个Controller,代码如下:
@RestController
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/user")
public String userMapping(@RequestBody User user){
userService.insertUser(user);
return "ok";
}
资源评论
weixin_38606811
- 粉丝: 6
- 资源: 982
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功