SpringBoot Mock单元测试详解

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就是创建一个类的虚假的对象,在测试环境中,用来替换掉真实的对象,以达到两大目的:

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

2. 添加依赖

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

 <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中添加依赖

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>

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

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

      <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(…)

例如:
given(userRepository.findByUserName(Mockito.anyString())).willReturn(user);

  • given + willReturn:

given用于对指定方法进行返回值的定制,它需要与will开头的方法一起使用
通过willReturn可以直接指定打桩的方法的返回值

when(userRepository.findByUserName(Mockito.anyString())).thenReturn(user);

  • when + thenReturn:
    when的作用与Given有点类似,但它一般与then开头的方法一起使用。
    thenReturn与willReturn类似,不过它一般与when一起使用。

在这里插入图片描述
在这里插入图片描述

发布了254 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/yangshengwei230612/article/details/104753603