Search code examples
javaunit-testingjunitmockingjmockit

In testing in java how to check if a method of an interface is called or not?


I want to test this class which calls a method of interface using anonymous class.

public class ClassToTest 
{
    public void methodToTest()
    {
        InterefaceToMock interefaceToMockReference = new InterefaceToMock() {

            @Override
            public int methodToMock()
            {
                return 0;
            }
        };
        interefaceToMockReference.methodToMock();
    }
}

This is the interface

public interface InterefaceToMock 
{
    public int methodToMock();
}

I am using this approch to check it methodToMock is called or not

import static org.junit.Assert.*;

import org.junit.Test;

import mockit.FullVerificationsInOrder;
import mockit.Mocked;
import mockit.NonStrictExpectations;
public class TestAClass 
{
    @Mocked InterefaceToMock interefaceToMockReferenceMocked;
    @Test
    public void test1()
    {
        new NonStrictExpectations()
        {
            {
                interefaceToMockReferenceMocked.methodToMock();times=1;
            }
        };
        (new ClassToTest()).methodToTest();
        new FullVerificationsInOrder(interefaceToMockReferenceMocked)
        {
        };
        assertTrue(true);
    }
}

But test case fails. Can anyone help.


Solution

  • Your original test was almost correct. It declared the mock field as simply being @Mocked, which merely gives you a single mocked instance implementing the interface, and this is not the one used by the code under test. The JMockit API has another mocking annotation, however, which extends mocking to all implementation classes from a given base type, and by default affects all instances of said classes. So, the test should be changed as follows:

    public class TestAClass 
    {
        @Capturing InterfaceToMock anyImplementingInstance;
    
        @Test
        public void test1()
        {
            new ClassToTest().methodToTest();
    
            new Verifications() {{
                anyImplementingInstance.methodToMock();
            }};
        }
    }