简体   繁体   中英

My mocked method returns the same instance on each call, how do I get it to return a new instance?

private mockedObject cpMock;

@Test
public void test() {

    Manager managerTest = new Manager(cpMock, size);

    Instance instance = new Instance(size);
    when(cpMock.requestInstance()).thenReturn(instance);

}

There's an overload for thenReturn , which has a var-arg parameter:

when(cpMock.requestInstance())
   .thenReturn(instance, instance1, instance2, instance3);

According to its javadocs, it will return these objects in that order. From the 4th call on, instance3 (last value) will be returned:

Sets consecutive return values to be returned when the method is called. Eg: when(mock.someMethod()).thenReturn(1, 2, 3);
Last return value in the sequence (in example: 3) determines the behavior of further consecutive calls.

thenReturn is good when all you're doing is returning a precomputed value. If you'd like to mock an instance to do something every time your method is called, then the right solution is an Answer (passed in with thenAnswer or doAnswer ), which is a single-method interface that works well with Java 8. You can get details about the invocation (including its arguments) with its InvocationOnMock parameter, and the return value of Answer.answer will act as the return value of the method.

This is also a good solution when you need your call to have side effects, like modifying its argument or calling a callback function.

when(cpMock.requestInstance()).thenAnswer(invocation => new Instance(size));

Without lambdas, the call is a little more verbose, but not too bad:

when(cpMock.requestInstance()).thenAnswer(new Answer<Instance>() {
  @Override public Instance answer(InvocationOnMock invocation) {
    return new Instance(size));
  }
}

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