[英]How to mock static methods using UnitilsJUnit4?
我在CustomerService
类中有方法getAllCustomers
。 在此方法内部,我从CustomerDao
类调用了另一个静态方法。 现在,当我在customerService
类中编写方法getAllCustomers
的junit时,我想在其中模拟对CustomerDao
静态方法即getAllCustomers
。 这是CustomerService
类中的getAllCustomers
方法的简短代码段。 是否可以使用unitils模拟静态方法调用?
Public static List<CustomerDate> getAllCustomers()
{
//some operations
List<CustomerDate> customers=CustomerDao.getAllCustomers();// static method inside CustomerDao
//some operations
}
上面的代码只是我要尝试的一个示例。 请避免讨论为什么将这些方法设计为静态方法。 那是一个单独的故事。)
这是一个问题:
因此,无需费力就静态调用,可以通过以下方法在PowerMock中进行设置:
@RunWith(PowerMockRunner.class)
@PrepareForTest(CustomerDao.class)
public class CustomerTest {
@Test
public void testCustomerDao() {
PowerMock.mockStatic(CustomerDao.class);
List<CustomerDate> expected = new ArrayList<CustomerDate>();
// place a given data value into your list to be asserted on later
expect(CustomerDao.getAllCustomers()).andReturn(expected);
replay(CustomerDao.class);
// call your method from here
verify(CustomerDao.class);
// assert expected results here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.