1
private mockedObject cpMock;

@Test
public void test() {

    Manager managerTest = new Manager(cpMock, size);

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

}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
Voldemort
  • 19
  • 2
  • 1
    You know that your example code doesn't initialize that mock? Please make sure you always post a [mcve] to avoid confusing your readers. – GhostCat Sep 21 '18 at 17:03
  • Pardon the reopen, but this is a slightly different question: You're not just returning different instances (which `thenReturn` is good for), but you're specifically asking about creating new instances. An Answer would be good for that. (I'll answer below.) – Jeff Bowman Sep 21 '18 at 18:09
  • Yes, you're correct, I'm trying to create new instances. – Voldemort Sep 21 '18 at 19:57

2 Answers2

4

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. E.g: when(mock.someMethod()).thenReturn(1, 2, 3);
Last return value in the sequence (in example: 3) determines the behavior of further consecutive calls.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
1

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));
  }
}
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251