zoukankan      html  css  js  c++  java
  • 用PowerMock spy mock private方法

    在实际的工作中,经常碰到只需要mock一个类的一部分方法,这时候可以用spy来实现。

    被测类:

    public class EmployeeService {
    
        public boolean exist(String userName) {
            checkPrivateExist(userName);
            checkPublicExist(userName);
            return true;
        }
    
        private void checkPrivateExist(String userName) {
            throw new UnsupportedOperationException();
        }
        
        public void checkPublicExist(String userName){
            throw new UnsupportedOperationException();
        }
    }

    如果要测试exist方法,需要mock checkPublicExist和checkPrivateExist方法,而不希望mock exist方法

    测试类:

    @PrepareForTest(EmployeeService.class)
    public class EmployeeServiceTestWithPrivateTest  extends PowerMockTestCase{
        
        @ObjectFactory
        public ITestObjectFactory getObjectFactory() {
            return new PowerMockObjectFactory();
        }
    
        @Test
        public void testExist() {
            try {
                EmployeeService service = PowerMockito.spy(new EmployeeService());
                PowerMockito.doNothing().when(service,"checkPrivateExist","powermock");
                PowerMockito.doNothing().when(service).checkPublicExist("powermock");;
                boolean result = service.exist("powermock");
                Assert.assertTrue(result);
                Mockito.verify(service).checkPublicExist("powermock");
                PowerMockito.verifyPrivate(service).invoke("checkPrivateExist","powermock");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }

    在测试类中,真实的调用了exist方法。

    需要注意的是对private方法的mock

    PowerMockito.doNothing().when(service,"checkPrivateExist","powermock");

    以及对exist方法调用过程的验证

    Mockito.verify(service).checkPublicExist("powermock");
    PowerMockito.verifyPrivate(service).invoke("checkPrivateExist","powermock");

  • 相关阅读:
    【转】numpy.random.randn()与rand()的区别
    【转】numpy.random.randn()与rand()的区别
    春节一顿饭,吃懂了分布式资源调度
    春节一顿饭,吃懂了分布式资源调度
    ASP.NET 分页类 简单好用 支持 AJAX 自定义文字
    系统设计摘录CAP
    webapi上传文件
    webuploader上传工具
    Js学习文件上传
    K-means算法Java实现
  • 原文地址:https://www.cnblogs.com/changzhz/p/5163562.html
Copyright © 2011-2022 走看看