In EasyMock, I'm familiar with the usual
EasyMock.expect(<an invocation of the function you want to mock>).andReturn(<the thing you want your mocked function to return)
pattern. E.g. if I have a function String getFoo() I could mock it so that it returns "foo" like this:
EasyMock.expect(getFoo()).andReturn("foo");
But what would using andAnswer allow me to do instead? The function names sound pretty similar and the EasyMock docs are pretty terrible. E.g. what can I do with
EasyMock.expect(getFoo()).andAnswer(...);
andReturn(...)is simpler. It will just direct the mocked function to return whatever you pass into theandReturncall. Given the example above,EasyMock.expect(getFoo()).andReturn("foo");will return"foo"when thegetFoo()function is first called in the course of testing.andAnswer(...)allow for more sophisticated mocking behaviour. Basically, it allows you to execute a lambda (which you pass in to theandAnswerfunction) when the mocked function is called during a test. You can use the lambda to dynamically generate the returned value (e.g. using the arguments that get passed into the mocked function when your business logic is invoked), or even to do things like modifying one of the function's input parameters (which you might want to do if your function has side effects). Here's an example: