简体   繁体   中英

What's the difference between EasyMock's .andReturn and .andAnswer methods?

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. Eg 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. Eg 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 the andReturn call. Given the example above, EasyMock.expect(getFoo()).andReturn("foo"); will return "foo" when the getFoo() 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 the andAnswer function) when the mocked function is called during a test. You can use the lambda to dynamically generate the returned value (eg 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:

expect(myMockedObject.aMethodThatMutatesAParameterAndReturnsSomething(...).andAnswer(
    () -> {
            final List<Foo> inputParamToMutate = (List<Foo>) EasyMock.getCurrentArguments()[0];
            inputParamToMutate.addAll(myFooMocks);
            return "my mocked string";
                
          }
);

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