单元测试|单元测试 @mock与@SpringBootTest的使用
目录
- 一.单元测试工具mock使用
- 1.引入依赖包
- 2.mock测试类
- 二.springboot使用@SpringBootTest单元测试
- 1.引入依赖包
- 2.测试类
- 三.mock和@springBootTest区别
- 1.mock进行单元测试不依赖spring的bean定义文件
- 2.@springBootTest需要启动服务
- 单元测试--SpringbootTest和MockMvc
- SpringbootTest
- MockMvc类的使用和模拟Http请求
- 相关API:
简单的说就是模拟这些需要构建的类或者资源,提供给需要测试的对象使用。
一.单元测试工具mock使用
1.引入依赖包
文章图片
2.mock测试类
文章图片
二.springboot使用@SpringBootTest单元测试 1.引入依赖包
文章图片
2.测试类
文章图片
三.mock和@springBootTest区别
1.mock进行单元测试不依赖spring的bean定义文件
不需要启动web服务,执行起来速度很快。
2.@springBootTest需要启动服务
执行真正的操作,执行速度慢,当需要真正的dao层操作时可选此测试方式。
单元测试--SpringbootTest和MockMvc
SpringbootTest
基于Junit 的Test
import junit.framework.TestCase; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class)//底层用junit的 SpringJUnit4ClassRunner@SpringBootTest(classes = {XdclassSpringbootApplication.class})public class XdclassSpringbootApplicationTests {@Testpublic void testOne() {System.out.println("start test"); Assert.assertEquals(1,1); TestCase.assertEquals(1,2); }}
当然也可以使用 @Before 和 @After , 和 junit 的测试一样。
启动类是必须要有的。
当有多个 @Test 的方法,需要一起执行的时候, 执行 XdclassSpringbootApplicationTests 这个类的 run或debug。
Assert 和 TestCase 都是 断言,用法一样。
MockMvc类的使用和模拟Http请求
相关API:
perform
:执行一个RequestBuilder请求andExpect
:添加ResultMatcher->MockMvcResultMatchers验证规则andReturn
:最后返回相应的MvcResult->Response
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @RunWith(SpringRunner.class)@SpringBootTest@AutoConfigureMockMvcpublic class MockMvcTestDemo {@Autowiredprivate MockMvc mockMvc; @Testpublic void apiTest(){try {MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/hello")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn(); } catch (Exception e) {e.printStackTrace(); }}}
【单元测试|单元测试 @mock与@SpringBootTest的使用】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
推荐阅读
- 女生该不该用小号测试男朋友()
- BNC公链|BNC公链 | Eth2.0测试网Topaz已质押超100万枚ETH
- 我的软件测试开发工程师书单
- 性能测试中QPS和TPS的区别
- 20180322【w4复盘日志】
- 如何在手机上查看测试vue-cli构建的项目
- 工作好忙
- 没有复用的cell|没有复用的cell 单元格的写法
- javascript|javascript 性能测试笔记
- 灵魂测试……