PowerMock 之进阶学习

  • 模拟局部变量 Mock Local Variable
    有返回值得局部变量的模拟!

这里的局部变量没有采取依赖注入的方式,而是采取了一种而是在方法内部 new出一个 EmployeeDao,我们通常都会写这样的代码,平时我们也可能或碰上这样的问题,那么我们怎么去解决这个问题呢!

public class EmployeeService {
public int getTotalEmployee()
{
    EmployeeDao employeeDao = new EmployeeDao();
    return employeeDao.getTotal();
}
}

说明:当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是需要mock的new对象代码所在的类。

getTotalEmployee()因为测试的时候是不能修改这个方法的,不管里面是什么东西,局部变量我们也是无法触摸的,所以!智能模拟,不能更改,这个改正很可能造成系统的缺陷。不注意就完了。非常的需要小心,作为测试人员的话!

/**
 * 采用 PowerMock 进行测试
*/
@Test
public void testGetTotalEmployeeWithMock() {
    EmployeeDao employeeDao = PowerMockito.mock(EmployeeDao.class);
    try {
        PowerMockito.whenNew(EmployeeDao.class).withNoArguments()//没得参数的够造!返回模拟的局部变量!
          .thenReturn(employeeDao);
        PowerMockito.when(employeeDao.getTotal()).thenReturn(10);
        EmployeeService service = new EmployeeService();
        int total = service.getTotalEmployee();
        assertEquals(10, total);
        } catch (Exception e)
         {
            fail("测试失败.");
         }
    }
}

而通过 Mock 方式测试的是成功的,当然您可能会非常惊讶 PowerMock 尽然有如此强大的能力,以至于可以
Mock 出局部变量。
* 局部变量的 void 方法

怎么进行测试呢?

public void createEmployee(Employee employee)
{
EmployeeDao employeeDao = new EmployeeDao();
employeeDao.addEmployee(employee);
}
@Test
public void testCreateEmployeeWithMock() {
     EmployeeDao employeeDao = PowerMockito.mock(EmployeeDao.class);
     try {
        PowerMockito.whenNew(EmployeeDao.class).withNoArguments()
            .thenReturn(employeeDao);
        Employee employee = new Employee();
        EmployeeService service = new EmployeeService();
        service.createEmployee(employee);
        Mockito.verify(employeeDao).addEmployee(employee);
        } catch (Exception e) {
          fail();
        }

于测试 void 返回类型的方法,同样我们做的只能是判断他是否被调用

  • mock static方法
public class ClassDependency {
    public static boolean isExist() {
     //do nothing
     return false; 
  } 

}
试用例代码:
@RunWith(PowerMockRunner.class) 
public class TestClassUnderTest {

    @Test 
    @PrepareForTest(ClassDependency.class) 
    public void testCallStaticMethod() {
        ClassUnderTest underTest = new ClassUnderTest();  
        PowerMockito.mockStatic(ClassDependency.class); 
        PowerMockito.when(ClassDependency.isExist()).thenReturn(true);
       Assert.assertTrue(underTest.callStaticMethod());
    }
}

Verifying
Verifying 是一个非常强大的测试工具,不仅在 powermock 中使用,就连 easymock,mockito 等框架都会使用,他的目的是为了检查某个被测试的方法是否顺利的被调用了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值