Java 如何用相同的方法模拟第二个对象?

Java 如何用相同的方法模拟第二个对象?,java,unit-testing,junit,mocking,mockito,Java,Unit Testing,Junit,Mocking,Mockito,现在我有了一个使用Mockito进行测试的方法。然而,这种方法有点复杂。在相同的方法中,我需要新的两个对象都是相同类型的 Timestamp beginTimestamp = new Timestamp(Long.parseLong(beginTimeLong)); Timestamp endTimestamp = new Timestamp(System.currentTimeMillis()); 我想模拟第二个对象,endTimestamp,以抛出一个异常,但我无法避免beginTimes

现在我有了一个使用Mockito进行测试的方法。然而,这种方法有点复杂。在相同的方法中,我需要新的两个对象都是相同类型的

Timestamp beginTimestamp = new Timestamp(Long.parseLong(beginTimeLong));
Timestamp endTimestamp = new Timestamp(System.currentTimeMillis());
我想模拟第二个对象,
endTimestamp
,以抛出一个
异常
,但我无法避免
beginTimestamp
的影响。现在我的问题是,如何仅模拟第二个对象,
endTimeStamp
,并使其在调用
endTimeStamp的
特定方法时抛出异常,例如:

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)