2013-04-22 50 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... 
} 

只有匹配記錄的預期將得到嘲笑的調用。當動態模擬類被調用時,其他人將執行真正的實現。