背景

工作中经常用到单测,某对单测掌握的不好,所以趁此学习、总结一下。

主要参考:https://www.jianshu.com/p/0c2480b1709e、https://www.cnblogs.com/ljw-bim/p/9391770.html

一、不依赖外部方法的单测

1、待测试类

  1. package com.shuimutong.demo.junit;
  2.  
  3. /**
  4. * 无依赖方法
  5. * @ClassName: NotStaticMethod
  6. * @Description:(这里用一句话描述这个类的作用)
  7. * @author: 水木桶
  8. * @date: 2019年10月26日 上午10:37:09
  9. * @Copyright: 2019 [水木桶] All rights reserved.
  10. */
  11. public class NoRelayMethod {
  12. public static int ADD_NUM = 2;
  13.  
  14. public static int staticAddTwo(int num) {
  15. return num + ADD_NUM;
  16. }
  17.  
  18. /**
  19. * 非静态方法
  20. * @param num
  21. * @return
  22. */
  23. public int notStaticAddTwo(int num) {
  24. return num + ADD_NUM;
  25. }
  26.  
  27. /**
  28. * 私有非静态方法
  29. * @param num
  30. * @return
  31. */
  32. private int privateNotStaticAddTow(int num) {
  33. return num + ADD_NUM;
  34. }
  35. }

2、单测类

  1. package com.shuimutong.demo.junit;
  2.  
  3. import java.lang.reflect.Method;
  4.  
  5. import org.junit.Assert;
  6. import org.junit.Test;
  7. import org.junit.runner.RunWith;
  8. import org.mockito.InjectMocks;
  9. import org.powermock.api.mockito.PowerMockito;
  10. import org.powermock.core.classloader.annotations.PrepareForTest;
  11. import org.powermock.modules.junit4.PowerMockRunner;
  12.  
  13. /**
  14. * 参照1:https://www.jianshu.com/p/0c2480b1709e
  15. * 参照2:https://www.cnblogs.com/ljw-bim/p/9391770.html
  16. * @ClassName: NoRelayMethodTest
  17. * @Description:(这里用一句话描述这个类的作用)
  18. * @author: 水木桶
  19. * @date: 2019年10月26日 下午4:14:48
  20. * @Copyright: 2019 [水木桶] All rights reserved.
  21. */
  22. @RunWith(PowerMockRunner.class)
  23. @PrepareForTest({NoRelayMethod.class})
  24. public class NoRelayMethodTest {
  25. @InjectMocks
  26. private NoRelayMethod noRelayMethod;
  27.  
  28. //不需要mock,可以去除上面3个注解
  29. @Test
  30. public void staticAddTwo() {
  31. int num = 3;
  32. int result = NoRelayMethod.staticAddTwo(num);
  33. Assert.assertTrue(result == (num + NoRelayMethod.ADD_NUM));
  34.  
  35. }
  36.  
  37. //不需要mock,可以去除上面3个注解
  38. @Test
  39. public void notStaticAddTwo() {
  40. int num = 1;
  41. NoRelayMethod noRelayMethod = new NoRelayMethod();
  42. int result = noRelayMethod.notStaticAddTwo(num);
  43. Assert.assertTrue(result == (num + NoRelayMethod.ADD_NUM));
  44. }
  45.  
  46. //需要mock
  47. //mock私有方法
  48. @Test
  49. public void privateNotStaticAddTow() throws Exception {
  50. Method method = PowerMockito.method(NoRelayMethod.class, "privateNotStaticAddTow", int.class);
  51. int num = 3;
  52. Object res = method.invoke(noRelayMethod, 3);
  53. System.out.println(res);
  54. Assert.assertEquals(num + NoRelayMethod.ADD_NUM, res);
  55. }
  56. }

3、备注

staticAddTwo和notStaticAddTwo方法不需要RunWith、PrepareForTest、InjectMocks这3个注解。

privateNotStaticAddTow涉及到私有方法,需要前面那3个注解。

二、有依赖外部静态方法的单测

1、待测试类

  1. package com.shuimutong.demo.junit;
  2.  
  3. /**
  4. * 有依赖其他静态方法
  5. * @ClassName: RelayMethod
  6. * @Description:(这里用一句话描述这个类的作用)
  7. * @author: 水木桶
  8. * @date: 2019年10月26日 下午3:26:01
  9. * @Copyright: 2019 [水木桶] All rights reserved.
  10. */
  11. public class RelayStaticMethod {
  12. public final static String DEFAULT_VAL = "defaultVal";
  13. public final static String SIGNED = "signed";
  14.  
  15. /**
  16. * 依赖静态方法的
  17. * @param key
  18. * @return
  19. */
  20. public String checkAndCalc(String key) {
  21. String returnVal = null;
  22. String savedVal = RedisUtil.get(key);
  23. if(savedVal == null || savedVal.length() < 1) {
  24. returnVal = DEFAULT_VAL;
  25. } else {
  26. returnVal = savedVal + "-" + SIGNED;
  27. }
  28. return returnVal;
  29. }
  30.  
  31. }

1-1、依赖外部类

  1. package com.shuimutong.demo.junit;
  2.  
  3. import java.util.UUID;
  4.  
  5. public class RedisUtil {
  6. private static boolean INIT_STATE = false;
  7.  
  8. public static String get(String key) {
  9. if(INIT_STATE) {
  10. return UUID.randomUUID().toString();
  11. } else {
  12. throw new NullPointerException("资源未初始化");
  13. }
  14. }
  15.  
  16. }

2、单测类

  1. package com.shuimutong.demo.junit;
  2.  
  3. import java.util.UUID;
  4.  
  5. import org.junit.Assert;
  6. import org.junit.Test;
  7. import org.junit.runner.RunWith;
  8. import org.mockito.Mockito;
  9. import org.powermock.api.mockito.PowerMockito;
  10. import org.powermock.core.classloader.annotations.PrepareForTest;
  11. import org.powermock.modules.junit4.PowerMockRunner;
  12.  
  13. @RunWith(PowerMockRunner.class)
  14. //参考:https://www.jianshu.com/p/0c2480b1709e
  15. //1、如果想要对某个类的静态方法进行mock,则必须在PrepareForTest后面加上相应的类名, 比如此例的RedisUtil.class。
  16. @PrepareForTest({RedisUtil.class})
  17. public class RelayStaticMethodTest {
  18. /**
  19. * mock依赖的静态方法
  20. */
  21. @Test
  22. public void checkAndCalc() {
  23. String key1 = "jack";
  24. String key2 = "john";
  25. String val2 = UUID.randomUUID().toString();
  26.  
  27. //2、在对该类的某个方法进行mock之前,还必须先对整个类进行mock
  28. PowerMockito.mockStatic(RedisUtil.class);
  29. PowerMockito.when(RedisUtil.get(Mockito.eq(key1))).thenReturn(null);
  30. PowerMockito.when(RedisUtil.get(Mockito.eq(key2))).thenReturn(val2);
  31.  
  32. RelayStaticMethod relayMethod = new RelayStaticMethod();
  33. String res = relayMethod.checkAndCalc(key1);
  34. System.out.println("res:" + res);
  35. Assert.assertEquals(RelayStaticMethod.DEFAULT_VAL, res);
  36.  
  37. res = relayMethod.checkAndCalc(key2);
  38. System.out.println("res:" + res);
  39. Assert.assertTrue(res.contains(RelayStaticMethod.SIGNED));
  40. }
  41.  
  42. }

2-1、运行结果

res:defaultVal
res:e76dc3b8-fcf5-42b8-9f79-1d308d137514-signed

三、有依赖外部非静态方法的单测

1、待测试类

  1. package com.shuimutong.demo.junit;
  2.  
  3. /**
  4. * 参照1:https://www.jianshu.com/p/0c2480b1709e
  5. * 参照2:https://www.cnblogs.com/ljw-bim/p/9391770.html
  6. * @ClassName: UserController
  7. * @Description:(这里用一句话描述这个类的作用)
  8. * @author: 水木桶
  9. * @date: 2019年10月26日 下午4:14:30
  10. * @Copyright: 2019 [水木桶] All rights reserved.
  11. */
  12. public class UserController {
  13. private UserService userService = new UserService();
  14.  
  15. public User saveUser(String name) {
  16. return userService.save(name);
  17. }
  18. }

1-1、依赖非静态类

  1. package com.shuimutong.demo.junit;
  2.  
  3. public class UserService {
  4. public User save(String name) {
  5. System.out.println("UserService--save--name:" + name);
  6. User u = new User(name);
  7. u.setId((long)(Math.random() * 1000) + 2);
  8. return u;
  9. }
  10. }

1-2、相关类User

  1. package com.shuimutong.demo.junit;
  2.  
  3. public class User {
  4. private long id;
  5. private String name;
  6.  
  7. public User(String name) {
  8. this.name = name;
  9. }
  10. public User() {
  11. }
  12.  
  13. public String getName() {
  14. return name;
  15. }
  16.  
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public long getId() {
  21. return id;
  22. }
  23. public void setId(long id) {
  24. this.id = id;
  25. }
  26. @Override
  27. public String toString() {
  28. return "User [id=" + id + ", name=" + name + "]";
  29. }
  30. }

2、单测类

  1. package com.shuimutong.demo.junit;
  2.  
  3. import org.junit.Assert;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.mockito.InjectMocks;
  7. import org.mockito.Mock;
  8. import org.mockito.Mockito;
  9. import org.powermock.api.mockito.PowerMockito;
  10. import org.powermock.core.classloader.annotations.PrepareForTest;
  11. import org.powermock.modules.junit4.PowerMockRunner;
  12.  
  13. /**
  14. * 参照1:https://www.jianshu.com/p/0c2480b1709e
  15. * 参照2:https://www.cnblogs.com/ljw-bim/p/9391770.html
  16. * @ClassName: UserControllerTest
  17. * @Description:(这里用一句话描述这个类的作用)
  18. * @author: 水木桶
  19. * @date: 2019年10月26日 下午4:13:51
  20. * @Copyright: 2019 [水木桶] All rights reserved.
  21. */
  22. @RunWith(PowerMockRunner.class)
  23. @PrepareForTest({UserController.class})
  24. public class UserControllerTest {
  25. @Mock
  26. private UserService userService;
  27. @InjectMocks
  28. private UserController userController;
  29.  
  30. @Test
  31. public void saveUser() {
  32. String name = "jack";
  33. //执行userService的实际方法
  34. PowerMockito.when(userService.save(Mockito.anyString())).thenCallRealMethod();
  35. User returnUser = userController.saveUser(name);
  36. System.out.println("returnUser:" + returnUser);
  37. Assert.assertTrue(returnUser.getId() > 1);
  38.  
  39. long id = 1L;
  40. User u1 = new User(name);
  41. u1.setId(id);
  42. System.out.println("u1:" + u1);
  43. //mock userService的方法
  44. Mockito.when(userService.save(name)).thenReturn(u1);
  45. returnUser = userController.saveUser(name);
  46. //verify验证mock次数
  47. Mockito.verify(userService, Mockito.times(2)).save(name);
  48. Assert.assertEquals(id, returnUser.getId());
  49. Assert.assertEquals(u1, returnUser);
  50. System.out.println("returnUser:" + returnUser);
  51. }
  52. }

2-1、执行结果

UserService--save--name:jack
returnUser:User [id=51, name=jack]
u1:User [id=1, name=jack]
UserService--save--name:jack
returnUser:User [id=1, name=jack]

四、相关环境

1、依赖jar

  1. <dependency>
  2. <groupId>junit</groupId>
  3. <artifactId>junit</artifactId>
  4. <version>4.11</version>
  5. <scope>test</scope>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.mockito</groupId>
  9. <artifactId>mockito-core</artifactId>
  10. <version>2.10.0</version>
  11. <scope>test</scope>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.powermock</groupId>
  15. <artifactId>powermock-api-mockito2</artifactId>
  16. <version>2.0.2</version>
  17. <scope>test</scope>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.powermock</groupId>
  21. <artifactId>powermock-module-junit4</artifactId>
  22. <version>2.0.2</version>
  23. <scope>test</scope>
  24. </dependency>

2、源码地址

https://gitee.com/simpleha/useDemo/tree/master/junit

Mock、Powermock使用汇总的更多相关文章

  1. 单元测试系列:Mock工具Jmockit使用介绍

    更多原创测试技术文章同步更新到微信公众号 :三国测,敬请扫码关注个人的微信号,感谢! 原文链接:http://www.cnblogs.com/zishi/p/6760272.html Mock工具Jm ...

  2. 单元测试系列之二:Mock工具Jmockit实战

    更多原创测试技术文章同步更新到微信公众号 :三国测,敬请扫码关注个人的微信号,感谢! 原文链接:http://www.cnblogs.com/zishi/p/6760272.html Mock工具Jm ...

  3. 有效使用Mock编写java单元测试

    Java单元测试对于开发人员质量保证至关重要,尤其当面对一团乱码的遗留代码时,没有高覆盖率的单元测试做保障,没人敢轻易对代码进行重构.然而单元测试的编写也不是一件容易的事情,除非使用TDD方式,否则编 ...

  4. spring boot 测试用例

    junit 是一个面向于研发人员使用的轻量的测试模块,适合做单元测试.而testng百度后发现更强大,可以做功能测试,但对于我这种RD,貌似junit足沟了呢! java Mock PowerMock ...

  5. Mock之easymock, powermock, and mockito

    easymock, powermock, and mockito Easymock Class Mocking Limitations To be coherent with interface mo ...

  6. 用PowerMock mock 由工厂方法产生的对象

    有些对象需要mock的对象是由工厂方法产生出来的,而工厂方法一般是静态方法,这时候就需要同时mock工厂方法及对象 被测方法: public class EmployeeServiceFactory ...

  7. 用PowerMock spy mock private方法

    在实际的工作中,经常碰到只需要mock一个类的一部分方法,这时候可以用spy来实现. 被测类: public class EmployeeService { public boolean exist( ...

  8. 用PowerMock mock static方法

    在编写代码时,经常需要调用别人已经写好的工具类,而这些工具提供的方法经常是static方法,在这里,直接贴出<PowerMock实战手册>中的例子 待测试方法: public class ...

  9. 用PowerMock mock 临时变量

    在开发时,经常遇到这种情况,被测试方法所调用的类不是通过构造注入的,而是通过临时new出来的,如下面待测方法: public class EmployeeService { private Emplo ...

随机推荐

  1. [web] 前端一些细节

    作者:水落斜阳链接:https://www.jianshu.com/p/7a8124fdf945来源:简书著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 1, reflow和re ...

  2. nginx https 转发

    add_header Content-Security-Policy upgrade-insecure-requests;

  3. nand flash 擦除指定的区域

    Nand falsh 在 u-boot 里面,是可以执行擦除操作的. 擦除整个 Nand 的命令: nand erase.chip 擦除部分区域 nand erase.spread 0x0 0x780 ...

  4. .Net Core 3.0 Api json web token 中间件签权验证和 Cors 中间件处理跨域请求

    第一步:在Nuget上安装"Microsoft.AspNet.WebApi.Cors"包,并对api controller使用[EnableCors]特性以及Microsoft.A ...

  5. 使用leaflet绘制geoJson中国边界

    绘制中国边界 代码如下: function drawChina() { //设置样式 var myStyle = { "color": "#00f", &quo ...

  6. PHP 指定时间/时间戳+某天/某月/某年

    PHP指定时间戳加上1天,1周,1月,一年其实是不需要用上什么函数的!指定时间戳本身就是数字整型,我们只需要再计算1天,1周它的秒数相加即可! 博主搜索php指定时间戳加一天一年,结果许多的文章给出来 ...

  7. Failed to open .vcf.gz: could not load index

    这类报错在我使用bcftools index file.vcf.gz进行index出现的. 解决办法是换用tabix进行index,命令为tabix -p vcf file.vcf.gz. 用tabi ...

  8. UltraISO制作启动U盘

    使用UltraISO可以制作纯净版本启动U盘 下载 下载地址https://cn.ultraiso.net/ 打开ISO镜像 下载后双击安装完成以后打开软件 文件-打开-选择一个ISO镜像,例如win ...

  9. Windows Server 2008 R2 IIS7.5配置FTP图文教程

    本文为大家分享了IIS 配置FTP 网站的具体过程,供大家参考,具体内容如下 说明:服务器环境是Windows Server 2008 R2,IIS7.5. 1. 在 服务器管理器的Web服务器(II ...

  10. kafka备份原理