当前位置 : 主页 > 编程语言 > java >

单元测试 @mock与@SpringBootTest的使用

来源:互联网 收集:自由互联 发布时间:2021-11-19
目录 一.单元测试工具mock使用 1.引入依赖包 2.mock测试类 二.springboot使用@SpringBootTest单元测试 1.引入依赖包 2.测试类 三.mock和@springBootTest区别 1.mock进行单元测试不依赖spring的bean定义文件
目录
  • 一.单元测试工具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.引入依赖包

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 {
    @Test
    public 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
@AutoConfigureMockMvc
public class MockMvcTestDemo {
    @Autowired
    private MockMvc mockMvc;
    @Test
    public void apiTest(){
        try {
            MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
                    .andExpect(MockMvcResultMatchers.status().isOk())            .andReturn();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持自由互联。

上一篇:Java实现红黑树(平衡二叉树)的详细过程
下一篇:没有了
网友评论