阅读 319

基于SpringBoot Mock单元测试详解

这篇文章主要介绍了基于SpringBoot Mock单元测试详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

目录
  • 1.Mock的概念:

  • 3. 常用的 Mockito 方法

Junit中的基本注解:

  • @Test:使用该注解标注的public void方法会表示为一个测试方法;

  • @BeforeClass:表示在类中的任意public static void方法执行之前执行;

  • @AfterClass:表示在类中的任意public static void方法之后执行;

  • @Before:表示在任意使用@Test注解标注的public void方法执行之前执行;

  • @After:表示在任意使用@Test注解标注的public void方法执行之后执行;

SpringBoot 单元测试详解(Mockito、MockBean)

SpringBoot 单元测试(cobertura 生成覆盖率报告)

1.Mock的概念:

所谓的mock就是创建一个类的虚假的对象,在测试环境中,用来替换掉真实的对象,以达到两大目的:

验证这个对象的某些方法的调用情况,调用了多少次,参数是什么等等指定这个对象的某些方法的行为,返回特定的值,或者是执行特定的动作 2. 添加依赖

新建的springBoot项目中默认包含了spring-boot-starter-test的依赖,如果没有包含可自行在pom.xml中添加依赖

1
2
3
4
5
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-test</artifactId>
       <scope>test</scope>
   </dependency>

在这里插入图片描述

进入 spring-boot-starter-test-2.2.2.RELEASE.pom 可以看到该依赖中已经有单元测试所需的大部分依赖,如:

  • junit

  • mockito

  • hamcrest

在这里插入图片描述

注意包含的junit为junit5 ,在主要还是使用junit4所以在pom.xml中添加依赖

1
2
3
4
5
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>

这里如果不添加的话,在使用@RunWith注解的时候也会提示你添加,点击Add ‘JUnit4' to classpath也会自动在pom.xml帮你添加

在这里插入图片描述


若为非springboot项目,其他 spring 项目,需要自己添加 Junit 和 mockito 的依赖。SpringBoot不要添加,添加后Test的时候会出错

1
2
3
4
5
6
7
8
9
10
11
12
13
<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
  </dependency>
  <!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
  <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.10.19</version>
      <scope>test</scope>
  </dependency>

3. 常用的 Mockito 方法

Mockito的使用,一般有以下几种组合:

  • do/when:包括doThrow(…).when(…)/doReturn(…).when(…)/doAnswer(…).when(…)

  • given/will:包括given(…).willReturn(…)/given(…).willAnswer(…)

  • when/then: 包括when(…).thenReturn(…)/when(…).thenAnswer(…)

例如:

1
given(userRepository.findByUserName(Mockito.anyString())).willReturn(user);
  • given + willReturn

given用于对指定方法进行返回值的定制,它需要与will开头的方法一起使用

通过willReturn可以直接指定打桩的方法的返回值

1
when(userRepository.findByUserName(Mockito.anyString())).thenReturn(user);
  • when + thenReturn

when的作用与Given有点类似,但它一般与then开头的方法一起使用。

thenReturn与willReturn类似,不过它一般与when一起使用。

在这里插入图片描述

在这里插入图片描述

以上为个人经验,希望能给大家一个参考

原文链接:https://blog.csdn.net/yangshengwei230612/article/details/104753603


文章分类
代码人生
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐