In a service test, how do I correctly set up a response from a mocked-out class?
I need to provide a response in the @BeforeScenario section of my service test. For example:
The problem is, the DTO is only created later on in the scenario. Since the response applies to several different scenarios and is different in each case it doesn't yet exist at the time the line above is encountered and Mockito throws a rather unhelpful exception. How do I get round this?
The important thing to note is that the content of thenReturn() is evaluated at the time the @BeforeScenario is executed. This means that the object - in this case a DTO - must already exist. However, you frequently want to return a value that is built as a result of setting up various @Given steps.
The key thing here is that the object instance that is available at the time the @BeforeScenario is executed must remain the same one through the scenario up to the point when the call to (in this case) checkSfsBookingStatus() is made. If your code substitutes a new object the mock will still return the old one and you won't see the value you expect.
Although you must keep the same object instance this does not prevent you from altering the content of that object. So if you construct a default object before the mocked response you can load it up with anything you like during the @Given steps, which allows the same mock to be used for several different scenarios.
I'm pretty sure you can use when().then() in places other than @BeforeScenario