2016-12-26 10 views
1

今私はMockitoを使ってテストする方法があります。しかし、この方法は複雑です。同じ方法で、私は新しい2つのオブジェクトが両方とも同じタイプである必要があります。2番目のオブジェクトを同じ方法でモックする方法は?

Timestamp beginTimestamp = new Timestamp(Long.parseLong(beginTimeLong)); 
Timestamp endTimestamp = new Timestamp(System.currentTimeMillis()); 

私はExceptionをスローするように、第二の目的、endTimestampをモックとしたいが、私はbeginTimestampの影響を回避することはできません。私が示されている私のテストコードを書くことを試みた

endTimestamp.getTime() 

:今、私の質問は、次のような、唯一の第二の目的、endTimeStampを、嘲笑する方法である、と私はendTimestamp's特定のメソッドを呼び出すときに例外をスローするようにします以下、

@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); 

は、私は問題を解決することができ、別の解決策はありますか?とにかく、問題が解決する場合にのみ、それはOKです。

答えて

2

代わりPowerMockito.whenNew(Timestamp.class).withAnyArguments().thenReturn(beginTimestamp).thenReturn(endTimestamp);

+0

のこの

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

を試してみてはとてもとてもとてもありがとう、それは働きます! –

関連する問題