简体   繁体   中英

How to mock the second object in the same method?

Now I have a method to test using Mockito . However the method is kind of complicated. In the same method ,I need to new two objects both are the same type.

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

I want to mock the second object , endTimestamp , to throw an Exception , but I can not avoid the influence of beginTimestamp . Now my question is how to mock the second object, endTimeStamp , only ,and make it to throw out an exception when I call endTimestamp's certain method ,such as:

endTimestamp.getTime()

I tried to write my test code which is shown below ,

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

It doesn't work either. These code don't have any red wavy underline ,but when I tried to run it, I got an exception like this:

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

Is there another solution I can solve the problem? Anyway , only if the problem to be solved ,that's OK.

Try this

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM