10

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?

4

1 回答 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.

于 2013-08-14T17:54:31.297 回答