现在我有一种使用Mockito测试的方法。但是,该方法很复杂。在同一方法中,我需要新两个对象都是相同的类型。
Timestamp beginTimestamp = new Timestamp(Long.parseLong(beginTimeLong));
Timestamp endTimestamp = new Timestamp(System.currentTimeMillis());
我想模拟第二个对象endTimestamp
,以扔Exception
,但我无法避免beginTimestamp
的影响。现在,我的问题是如何模拟第二个对象endTimeStamp
,并在我调用endTimestamp's
某些方法时使其抛出一个例外,例如:
endTimestamp.getTime()
我试图编写下面显示的测试代码,
@Ignore
public void getSynPotentialShopBeginTimeAndEndTest4() throws Exception {
Timestamp beginTimestamp = PowerMockito.mock(Timestamp.class);
Timestamp endTimestamp = PowerMockito.mock(Timestamp.class);
PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp).thenReturn(endTimestamp);
when(endTimestamp.getTime()).thenThrow(RuntimeException.class);
redisService.getSynPotentialShopBeginTimeAndEnd();
}
它也行不通。这些代码没有任何红色波浪的下划线,但是当我尝试运行它时,我得到了这样的例外:
org.mockito.exceptions.base.MockitoException:
Incorrect use of API detected here:
You probably stored a reference to `OngoingStubbing` returned by `when()` and called stubbing methods like `thenReturn()` on this reference more than once.
Examples of correct usage:
when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception);
when(mock.isOk()).thenReturn(true, false).thenThrow(exception);
我可以解决另一个解决方案吗?无论如何,只有在解决问题时才可以。
尝试此
PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp,endTimestamp);
而不是PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp).thenReturn(endTimestamp);