单元测试|单元测试 @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。
简单的说就是模拟这些需要构建的类或者资源,提供给需要测试的对象使用。

一.单元测试工具mock使用

1.引入依赖包
单元测试|单元测试 @mock与@SpringBootTest的使用
文章图片


2.mock测试类
单元测试|单元测试 @mock与@SpringBootTest的使用
文章图片


二.springboot使用@SpringBootTest单元测试 1.引入依赖包
单元测试|单元测试 @mock与@SpringBootTest的使用
文章图片


2.测试类
单元测试|单元测试 @mock与@SpringBootTest的使用
文章图片


三.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的使用】以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

    推荐阅读