首页 > 其他分享 >Spring Boot 单元测试笔记

Spring Boot 单元测试笔记

时间:2022-12-03 19:46:05浏览次数:40  
标签:String Spring Boot param 单元测试 OrderParam DemoOrder public order1

1. 导入JUnit5测试框架

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.8.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.8.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <version>5.7.2</version>
    <scope>test</scope>
</dependency>

其他按 Spring Boot 项目标准,按需引入即可

2. 编写Service

/**
 * 假设一个订单类
 */
public class DemoOrder {
    private String orderId;
    private String orderUser;
    private String contents;
    private Integer quantity;
    private BigDecimal price;
    private BigDecimal total;

    // getter,setter略
}

Mapper 接口

@Mapper
public interface DemoOrderMapper {
    DemoOrder selectOrderByOrderId(String orderId);
    List<DemoOrder> selectOrderByOrderParam(OrderParam param);
}

Service

/**
 * DemoService
 * 此处的两个方法,一个是传入String,一个是传入封装好的参数类 OrderParam。这两种方法的测试方法不同
 */
public interface DemoService {
    DemoOrder findOrderByOrderId(String orderId);
    DemoOrder findOrderByRequestParam(OrderParam param);
}
@Service
public class DemoServiceImpl implements DemoService {
    @Autowired
    DemoMapper demoMapper;

    @Override
    public DemoOrder findOrderByOrderId(String orderId) {
        DemoOrder order = demoMapper.selectOrderByOrderId(orderId);
        return order;
    }

    @Override
    public DemoOrder findOrderByRequestParam(OrderParam param) {
        List<DemoOrder> orderList = demoMapper.selectOrderByRequestParam(param);
        return CollectionUtils.isEmpty(orderList) ? null : orderList.get(0);
    }
}

3. 编写测试类

@DisplayName("单元测试用例")
public class DemoServiceTest {
    @InjectMocks
    DemoServiceImpl demoService; // 此处注意要使用Service接口的实现类

    @Mock
    DemoMapper demoMapper; // 对Mapper使用Mock

    @BeforeEach
    public void setUp() {
        openMocks(this);
        // 老版本是 initMocks(this);
        // 准备数据
        DemoOrder order1 = new DemoOrder();
        order1.setOrderId("001");
        order1.setOrderUser("User1");
        order1.setContents("contents1");
        order1.setQuantity(1);
        order1.setPrice(new BigDecimal("10.5"));
        order1.setTotal(new BigDecimal("10.5"));

        DemoOrder order2 = new DemoOrder();
        order2.setOrderId("002");
        // ... 其他属性略

        DemoOrder order3 = new DemoOrder();
        order3.setOrderId("003");
        // ... 其他属性略

        // 以下为mock mapper的方法模拟
        // 1. 传String的方法,直接传入模拟的参数即可
        when(demoMapper.selectOrderByOrderId("001")).thenReturn(order1);
        when(demoMapper.selectOrderByOrderId("002")).thenReturn(order2);
        // ...

        // 2. 传OrderParam的方法,需要将 when...thenReturn语法改为 doReturn...when... 语法
        doReturn(Collections.singletonList(order1))
            .when(demoMapper).selectOrderByOrderParam(argThat(
                new ArgumentMatcher<OrderParam>() {
                    @Override
                    public boolean match(OrderParam param) {
                        return param.getOrderId().equals("001")
                    }
                }
        ));
        // 此处也可以将 ArgumentMatcher 单独定义

        doReturn(Collections.singletonList(order2))
            .when(demoMapper).selectOrderByOrderParam(argThat(
                new ArgumentMatcher<OrderParam>() {
                    @Override
                    public boolean match(OrderParam param) {
                        return param.getOrderId().equals("002")
                    }
                }
        ));
    }

    @Test
    public void findOrderByOrderIdTest() {
        String orderId = "001";
        DemoOrder order = demoService.findOrderByOrderId(orderId);

        assertThat(order.getOrderUser()).isEqualTo("User1");
    }

    @Test
    public void findOrderByOrderParamTest() {
        OrderParam param = new OrderParam();
        param.setOrderId("002");
        DemoOrder order = demoService.findOrderByOrderParam(param);

        assertThat(order.getOrderUser()).isEqualTo("User2"); 
    }
}

标签:String,Spring,Boot,param,单元测试,OrderParam,DemoOrder,public,order1
From: https://www.cnblogs.com/ryuasuka/p/16948637.html

相关文章

  • SpringCloud+MyBatis+Redis整合—— 超详细实例
    SpringCloud+MyBatis+Redisredis①是一种nosql数据库,以键值对<key,value>的形式存储数据,其速度相比于MySQL之类的数据库,相当于内存读写与硬盘读写的差别,所以常常用作缓存,用......
  • 基于CV1811C uboot显示logo
    1.根据原理图在dts中配置panel的reset、power等管脚,uboot和kernel吃的是同一份dts2.panel初始化参数在u-boot-2021.10/include/cvitek/cvi_panels/dsi_hx8394_evb.h......
  • SpringCloud游戏平台改造-Day1
    Day1今天主要的工作是有,新建项目结构(后期可能会根据实际情况修改),实现了登录注册API项目思路目前的项目思路为以下几部分:GameAuth:用来提供用户登录注册接口,认证接口......
  • SpringCloud游戏平台改造-Day2
    Day2今天主要目的是接入SpringSecurity和JWT,不多说开干!Day1Day2接入SpringSecurityStep1实现来自SpringSecurity的UserDetailService接口,实现它的loaduserByUser......
  • SpringCloud Alibaba(七) - JWT(JSON Web Token)
    原文链接:JWT详解:https://blog.csdn.net/weixin_45070175/article/details/1185592721、什么是JWT通俗地说,JWT的本质就是一个字符串,它是将用户信息保存到一个Json字符串......
  • hud:Being a Good Boy in Spring Festival(nim博弈方法数计算)
    ProblemDescription一年在外父母时刻牵挂春节回家你能做几天好孩子吗寒假里尝试做做下面的事情吧陪妈妈逛一次菜场悄悄给爸爸买个小礼物主动地强烈地要求洗一次碗......
  • spring bean是什么
    转载:https://www.awaimai.com/2596.html Spring有跟多概念,其中最基本的一个就是bean,那到底springbean是什么?Bean是Spring框架中最核心的两个概念之一(另一个是面向切......
  • Spring MVC请求地址映射详解:HandlerMapping
    1HandlerMapping介绍HandlerMapping是SpringMVC的核心组件之一,用来保存request-handler之间的映射。简单来说,request指的是请求地址(还包括请求方法等),handler指的是Cont......
  • spring boot下的三种包扫描
    扫描的包名是:资源名(Sourcename)//启动类扫描@SpringBootApplication(scanBasePackages={"springcloud.client01","springcloud.common.db.utils"})//mapper注解扫描......
  • 【SpringBoot】对于yaml的详细学习和三种属性赋值的实战详解
    一.yaml详细讲解1.1什么是yaml?YAML是一种数据序列化语言,通常用于编写配置文件。业界对YAML有不同的看法。有些人会说YAML代表另一种标记语言。其他人认为“YAML不是标记......