2015-05-14 147 views
2

我將在Util類中模擬名爲toBeMockedFunction的靜態函數。該方法從調用到BeUnitTested這是一個公共靜態無效方法。我想要讓BeMockedFunction不做任何事情。我嘗試了很多方法(片段貼出這樣的2個)部分模擬和存根並且無法成功。無法使用PowerMockito部分模擬靜態方法

請建議我做錯了什麼。

public class Util { 
    // Some code 
    public static void toBeUnitTested(CustomObject cb, CustomObject1 cb1, List<CustomObject2> rows, boolean delete) { 
     // some code 

     toBeMockedFunction(cb, "test", "test"); 
    } 

    public static CustomObject toBeMockedFunction(CustomObject cb, String str1) { 
     // some code 
    } 

} 

而下面是我JUnit類

@RunWith(PowerMockRunner.class) 
@PrepareForTest({ Util.class}) 
public class UtilTest { 
    @Test 
    public void Test1() { 
     PowerMockito.spy(Util.class);    

//mock toBeMocked function and make it do nothing 
PowerMockito.when(PowerMockito.spy(Util.toBeMockedFunction((CustomObject)Mockito.anyObject(), Mockito.anyString()))).thenReturn(null); 

     Util.toBeUnitTested(cb, "test", "test"); 
    } 
    } 
  • Approach2

    PowerMockito.mockStatic(Util.class); 
        PowerMockito.when(Util.toBeUnitTested((CustomObject)Mockito.anyObject(),Mockito.anyString())).thenCallRealMethod(); 
        Util.toBeUnitTested(cb, "test", "test"); 
    
  • 回答

    2

    這是如何能做到這一點的例子:

    @RunWith(PowerMockRunner.class) 
    @PrepareForTest({ Util.class}) 
    public class UtilTest { 
        @Test 
        public void Test1() { 
    
         PowerMockito.spy(Util.class); 
         PowerMockito.doReturn(null).when(Util.class, "toBeMockedFunction", Mockito.any(CustomObject.class), Mockito.anyString(), Mockito.anyString()); 
    
         List<CustomObject2> customObject2List = new ArrayList<>(); 
         customObject2List.add(new CustomObject2()); 
    
         Util.toBeUnitTested(new CustomObject(), new CustomObject1(), customObject2List, true); 
        } 
    } 
    

    請注意,OP的代碼不能編譯。方法toBeMockedFunction(CustomObject cb, String str1)只收到2個參數,並且您使用3:toBeMockedFunction(cb, "test", "test");進行呼叫。如您所見,我已將最後一個添加到方法簽名中。

    希望它有幫助

    +1

    PowerMockito.mockStatic(Util.class);將嘲笑類的所有靜態方法,包括toBeUnitTested()函數。它的定義永遠不會被調用。 – sandy

    +0

    對不起,沒錯。請看我的編輯。 – troig