zoukankan      html  css  js  c++  java
  • 用PowerMock mock 由工厂方法产生的对象

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

    被测方法:

    public class EmployeeServiceFactory {
        public void saveEmployee(Employee employee){
            EmployeeDaoFactory dao = EmployeeDaoFactory.newInstance();
            method("powermock");
            dao.addEmployee(employee);
        }
        
        public void method(String str){
            throw new UnsupportedOperationException();
        }
    }
    public class EmployeeDaoFactory {
        private EmployeeDaoFactory(){
            
        }
        
        public static EmployeeDaoFactory newInstance(){
            return new EmployeeDaoFactory();
        }
        
        public void addEmployee(Employee employee) {
            throw new UnsupportedOperationException();
        }
        
    }

    测试类:

    @PrepareForTest(value={EmployeeDaoFactory.class})
    public class EmployeeServiceTestFactoryTest  extends PowerMockTestCase{
        
        @ObjectFactory
        public ITestObjectFactory getObjectFactory() {
            return new PowerMockObjectFactory();
        }
        
        @Test
        public void addEmployee(){
            EmployeeDaoFactory employeeDao = PowerMockito.mock(EmployeeDaoFactory.class);
            try {
                PowerMockito.mockStatic(EmployeeDaoFactory.class);
                PowerMockito.when(EmployeeDaoFactory.newInstance()).thenReturn(employeeDao);
                EmployeeServiceFactory  service = PowerMockito.spy(new EmployeeServiceFactory());
                PowerMockito.doNothing().when(service).method(Mockito.anyString());
                Employee employee = new Employee();
                service.saveEmployee(employee);
                Mockito.verify(service).method("powermock");
                Mockito.verify(employeeDao).addEmployee(employee);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    关于亮剑,文化大革命的一点感想
    iOS -- block
    runtime -- 方法交换的坑自定义方法不执行
    iOS-UITableViewCell
    iOS debug模式
    iOS 将storybord中的视图与viewcontroller相关联
    gitignore的编写规则
    使用cocopods安装Alamofire后各种报错
    ReactNative--坑--'React/RCTBridgeModule.h' file not found
    12-2描点 学完路径可以对整个工具条做个概括 绘图类已完成
  • 原文地址:https://www.cnblogs.com/changzhz/p/5163651.html
Copyright © 2011-2022 走看看