Mocking static method that is called multiple times

一曲冷凌霜 提交于 2021-01-27 14:52:58

问题


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());
         }
    }
}

回答1:


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.



来源:https://stackoverflow.com/questions/16145359/mocking-static-method-that-is-called-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!