2013-04-22 85 views
3

我有一个静态方法,在多个地方使用,主要是静态初始化块。它将一个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()); 
     } 
    } 
} 

回答

4

你想要的是“偏嘲弄”的形式,在JMockit API在具体dynamic partial mocking

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

    // Call tested code... 
} 

只有匹配记录的预期将得到嘲笑的调用。当动态模拟类被调用时,其他人将执行真正的实现。