11

I'm trying to achieve this behavior with Mockito:

When object of type O is applied to a method M, the mock should execute another method on the object of type O passing itself as a parameter.

Is it possible after all?

1 Answer 1

11

You can probably use some combination of doAnswer and the when combined with Mockito.any. doAnswer is a part of PowerMockito, which helps extend a lot of the mocking you may want to do.

NOTE, doAnswer is used as an example for void functions. For a non-void you can use your standard Mockito.when(MOCK.call).then(RESULT)

PowerMockito.doAnswer(new org.mockito.stubbing.Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        //Do whatever to Object O here.
        return null;
    }).when(MOCKOBJECT.methodCall(Mockito.any(O.class)));

This then does the helpful doAnswer functionality on a mock object, and using the when you can assign it to catch for any specific class of object (instead of having to specify an exact object it should be expecting). Using the Mockito.any(Class.class)) as part of the parameters lets Mockito know to fire off your doWhatever, when it hits a method call with ANY object of the specified type passed in.

4
  • 13
    You don't need PowerMockito for this, you can just write when(MOCKOBJECT.methodCall(any(O.class))).thenAnswer(new Answer<...>() { ... }); Aug 14, 2013 at 19:22
  • Good catch, it's tricky sometimes to pull out examples cleanly because all my mock tests are just an amalgm of calls for static/non-static calls.
    – Walls
    Aug 14, 2013 at 19:42
  • 5
    Don't use PowerMockito. As far as I can see, there's no need for it here. Mockito has a doAnswer method, which does precisely what you need. The solution given here (except with Mockito.doAnswer instead of PowerMockito.doAnswer) should work fine for you; if it doesn't, check the Mockito documentation for doAnswer. The solution given by Tavian, using when and thenAnswer will work too, if the method that you want to stub is not void. Aug 14, 2013 at 20:45
  • 2
    doAnswer() is part of mockito-core-1.10.19.jar, no need to use PowerMockito
    – To Kra
    Jul 13, 2016 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.