2016-12-26 116 views
1

现在我有一个方法来测试使用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); 

有另一种解决方案,我可以解决这个问题?无论如何,只有当问题得到解决,没关系。

回答

2

试试这个

PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp,endTimestamp); 

而不是PowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp).thenReturn(endTimestamp);

+0

谢谢你这么这么这么多,它的工作原理! –

相关问题