用PowerMock mock 临时变量

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

public class EmployeeService {
    private EmployeeDao employeeDao;


    public int getTotalEmployeeWithTempVariable() {
        EmployeeDao employeeDao = new EmployeeDao();
        return employeeDao.getTotal();
    }
}

employeeDao是临时new出来的,而mockito和easyMock一般是通过代理来实现mock,这时就无法mock此类方法了。

而PowerMock通过直接修改class,使这类方法可测,

@PrepareForTest(EmployeeService.class)
public class EmployeeServiceTest extends PowerMockTestCase {

    EmployeeService employeeService;

    @ObjectFactory
    public ITestObjectFactory getObjectFactory() {
        return new PowerMockObjectFactory();
    }
    @BeforeMethod
    public void init(){
         employeeService = new EmployeeService(employeeDao);
    }
    
    @Test
    public void testGetTotalEmployeeWithTempVariable() {
        try {
            PowerMockito.whenNew(EmployeeDao.class).withNoArguments()
                    .thenReturn(employeeDao);
            PowerMockito.when(employeeDao.getTotal()).thenReturn(10);
            int total = employeeService.getTotalEmployeeWithTempVariable();
            assertEquals(10, total);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这里有三个很重要的地方:

@PrepareForTest(EmployeeService.class):告诉PowerMock,需要修改EmployeeService的class文件

@ObjectFactory:告诉testNG以对象工厂的形式创建测试实例

extends PowerMockTestCase :继承此接口

此外需要

PowerMockito.whenNew(EmployeeDao.class).withNoArguments()
.thenReturn(employeeDao);

录制EmployeeDao的构造行为并返回实例

posted @ 2016-01-27 09:33  xjzcz  阅读(2591)  评论(0编辑  收藏  举报