模拟多次调用的静态方法

时间:2013-04-22 10:53:32

标签: java junit4 jmockit

我有一个静态方法,用于多个地方,主要是在静态初始化块中。它将Class对象作为参数,并返回类的实例。 我想只在特定的Class对象用作参数时才模拟这个静态方法。但是当从其他地方调用该方法时,使用不同的Class对象,它将返回null。
如果参数不是被模拟的参数,我们如何让静态方法执行实际的实现?

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 个答案:

答案 0 :(得分:4)

你想要的是一种“部分模拟”,特别是JMockit API中的dynamic partial mocking

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

    // Call tested code...
}

只有与记录的期望匹配的调用才会被嘲笑。其他人将在调用动态模拟类时执行实际实现。

相关问题