Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify method invocation without executing its actual implementation on a Spy

Let's assume the following test

public void someTest() throws Exception {
   Foo foo = spy(new Foo());
   foo.someMethod(); // invokes methodToBeVerified()
   verify(foo).methodToBeVerified();
}

When the test executes it calls the actual implementation of foo.methodToBeVerified(). I would like the test to verify whether that particular method has been called or not but I do not want its implementation to be to executed. Is it possible to do that using Mockito's Spy?

like image 264
Rajib Deka Avatar asked Oct 29 '25 00:10

Rajib Deka


1 Answers

Yes, using

doNothing().when(foo).methodToBeVerified();

as in the following example

public class FooTest {

    static class Foo {

        public void someMethod() {
            System.out.println("someMethod called");
            System.out.println("calling method to be verified...");
            methodToBeVerified();
        }

        public void methodToBeVerified() {
            System.out.println("methodToBeVerified called");
        }
    }

    @Test
    public void someTest() throws Exception {
        Foo foo = spy(new Foo());
        doNothing().when(foo).methodToBeVerified();
        foo.someMethod();
        verify(foo).methodToBeVerified();
    }

}

For reference, what you are looking for is called Partial Mocks. Real (spied) partial mocks are supported in Mockito since 1.8.0.

like image 197
Ivo Mori Avatar answered Oct 30 '25 16:10

Ivo Mori