Search code examples
javajmockit

JMockit Capture and replace interface method logic


How can you capture the calling of an interface method and replace the captured interface method's logic with the mocked one, using JMockit?


Solution

  • Yes, it is clearly described in "The JMockit Tutorial", here: http://jmockit.googlecode.com/svn/trunk/www/tutorial/StateBasedTesting.html#interfaces

    Here comes the copy-pasted example of code that mocks the CallBackHandler interface and provides own implementation of the handle method:

    @Test
    public void mockingAnInterface() throws Exception
    {
        CallbackHandler callbackHandler = new MockUp<CallbackHandler>() {
            @Mock
             void handle(Callback[] callbacks)
             {
                 assertEquals(1, callbacks.length);
                 assertTrue(callbacks[0] instanceof NameCallback);
             }
        }.getMockInstance();
    
        callbackHandler.handle(new Callback[] {new NameCallback("Enter name:")});
    }