0

getAllCustomersCustomerService课堂上有方法。在这个方法中,我从CustomerDao类中调用另一个静态方法。现在,当我getAllCustomerscustomerService类中为方法编写 junit 时,我想在其中模拟对CustomerDaoie的静态方法的调用getAllCustomersgetAllCustomers这是类内部 方法的简短代码片段CustomerService是否可以使用 unitils 模拟静态方法调用?

Public static List<CustomerDate> getAllCustomers()
{
//some operations
List<CustomerDate> customers=CustomerDao.getAllCustomers();// static method inside CustomerDao
//some operations
}

上面的代码只是我试图提出的一个例子。请避免讨论为什么这些方法被设计为静态方法。那是一个单独的故事。)

4

2 回答 2

0

我怀疑它是否可以用unitils实现。但请考虑改用PowerMock,它似乎能够处理你需要的东西。它可以模拟静态方法、私有方法等(参考:PowerMock

于 2012-12-24T05:48:31.297 回答
0

这将是一个问题:

  • 设置模拟
  • 调用模拟并期望返回一些数据
  • 根据您的数据验证通话的最终结果

所以,不用多说关于静态调用,这里是您可以在 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
    }
}
于 2012-12-24T06:08:50.700 回答