温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

基于SpringBoot Mock单元测试的示例分析

发布时间:2021-11-23 08:53:38 来源:亿速云 阅读:297 作者:小新 栏目:开发技术

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

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

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

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

基于SpringBoot Mock单元测试的示例分析

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

  • junit

  • mockito

  • hamcrest

基于SpringBoot Mock单元测试的示例分析

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

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

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

基于SpringBoot Mock单元测试的示例分析

若为非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一起使用。

基于SpringBoot Mock单元测试的示例分析

基于SpringBoot Mock单元测试的示例分析

看完了这篇文章,相信你对“基于SpringBoot Mock单元测试的示例分析”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI