In a service test, how do I correctly set up a response from a mocked-out class?

21 months ago by

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?

2 Answers

21 months ago by

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.

21 months ago by

I'm pretty sure you can use when().then() in places other than @BeforeScenario

No matter where it's done the reference that's returned must be non-null at the time of executing the when(), or an exception will be thrown. As far as I can tell the exception fails to mention that the cause was a null pointer. It appears that no examination is made of the contents of the returned object so it's quite OK to populate it later. The when() statement computes the value of the .thenReturn() expression and holds onto it from that point on, so if your subsequent code substitutes a new reference this will be ignored; you'll still get back the original one for the item being mocked and the test will fail or at least be invalid.

written 21 months ago by Graham Trott 
Please login to add an answer/comment or follow this question.

Similar posts:
Search »