【发布时间】:2015-01-13 07:36:11
【问题描述】:
在这种情况下是否可以使用 Mockito、PowerMock 或任何其他模拟对象生成器模拟 RentalProfile.getStartDate()?
我尝试过这样做,但没有成功:
@Test
public void testsetAmortizationModel() throws Exception {
// ...
RentalProfile mock = Mockito.mock(RentalProfile.class);
Mockito.when(mock.getStartDate()).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
return "2014-12-21";
}
});
Mockito.verify(mock);
// ...
}
还有一种方法是调用 RentalProfile.getStartDate()。它不返回“2014-12-21”:
public void classMethod() {
List<RentalProfile> tPaymentPlans =
aCompositeAgreement.getRentalProfiles().getRentalProfile();
// ...
for (RentalProfile tRentalProfile : tPaymentPlans) {
LocalDate tStartDate = BridgeDateUtils.stringWithHyphenToDate(
tRentalProfile.getStartDate()); // tRentalProfile is RentalProfile object
// ...
}
【问题讨论】:
-
您确定您的
tRentalProfile与mock是同一个实例吗?如果它是同一个实例,它应该可以工作。当你模拟一个类时,你创建了一个你必须在测试中使用的模拟实例。它不会修改该类所有实例的行为。 -
你也可以简化模拟:
when(mock.getStartDate()).thenReturn("2014-12-21"); -
做了一些修改。这就是
tRentalProfile的创建方式。
标签: java unit-testing mocking