Search code examples
javajunit4jmockit

Mocking static method that is called multiple times


I have a static method, that is used in multiple places, mostly in static initialization block. It takes a Class object as parameter, and returns the class's instance. I want to mock this static method only when particular Class object is used as parameter. But when the method is called from other places, with different Class objects, it returns null.
How can we have the static method execute actual implementation in case of parameters other than the mocked one?

class ABC{
    void someMethod(){
        Node impl = ServiceFactory.getImpl(Node.class); //need to mock this call
        impl.xyz();
    }
}

class SomeOtherClass{
    static Line impl = ServiceFactory.getImpl(Line.class); //the mock code below returns null here
}


class TestABC{
    @Mocked ServiceFactory fact;
    @Test
    public void testSomeMethod(){
         new NonStrictExpectations(){
              ServiceFactory.getImpl(Node.class);
              returns(new NodeImpl());
         }
    }
}

Solution

  • What you want is a form of "partial mocking", specifically dynamic partial mocking in the JMockit API:

    @Test
    public void testSomeMethod() {
        new NonStrictExpectations(ServiceFactory.class) {{
            ServiceFactory.getImpl(Node.class); result = new NodeImpl();
        }};
    
        // Call tested code...
    }
    

    Only the invocations that match a recorded expectation will get mocked. Others will execute the real implementation, when the dynamically mocked class is called.