2012-08-14 147 views
3

說明:PowerMockito嘲諷whenNew不採取影響

我似乎無法讓我的存根或嘲笑的I類有下試生效。我正在嘗試使用whenNew操作,所以我可以模擬一個返回對象,然後用一個返回值模擬該對象的操作。

我想像它簡單的東西,我失蹤,但沒有看到它。

解決方案:最初我使用MockitoRunner.class運行,它需要更改爲PowerMockRunner.class。以下代碼反映瞭解決方案。在classpath

罐: powermock-的Mockito-1.4.11-full.jar mockoito,全1.9.0.jar 了Javassist-3.15.0-GA.jar 的JUnit 4.8.2.jaf objensis-1.2.jar CGLIB的節點p-2.2.2.jar

測試類

import org.junit.Test; 
    import org.junit.runner.RunWith; 
    import org.powermock.api.mockito.PowerMockito; 
    import static org.powermock.api.mockito.PowerMockito.*; 
    import org.powermock.core.classloader.annotations.PrepareForTest; 
    import org.powermock.modules.junit4.PowerMockRunner; 
    import static org.mockito.Matchers.any; 
    @RunWith(PowerMockRunner.class) 
    @PrepareForTest(ClassA.class) 
    public class ClassATest { 

     @Test 
     public void test() throws Exception 
     { 
       String[] returnSomeValue = {"PowerMockTest"}; 
       String[] inputValue = {"Test1"}; 
       ClassB mockedClassB = mock(ClassB.class); 
       whenNew(ClassB.class).withNoArguments().thenReturn(mockedClassB); 
       when(mockedClassB, "getResult", any(String[].class)).thenReturn(returnSomeValue);  

       IClassA classUnderTest = new ClassA(); 
       String[] expectedValue = classUnderTest.runTest(inputValue);  
     } 

    } 

A級實施

public class ClassA implements IClassA { 

    @Override 
    public String[] runTest(String[] inputValues) { 

     String[] result; 
     IClassB classB = new ClassB(); 
     result = classB.getResult(inputValues); 

     return result; 
    } 

} 
+0

@gontard更換

when(mockedClassB, "getResult", any(String[].class)).thenReturn(someValue); 

- 更新。 – haju 2012-08-14 23:25:39

回答

7

由於使用powermock功能(@PrepareForTestPowerMockito.whenNew等),你必須運行與PowerMockRunner測試。

@RunWith(PowerMockRunner.class) 

因爲ClassB的#geResult不是私人的,你也可以簡化您的代碼,並通過

when(mockedClassB.getResult(any(String[].class))).thenReturn(someValue); 
+0

試過了,它在任何(String []。類)上都失敗了)說:「在這裏檢測到錯誤的參數匹配,看起來像是在模擬時很難傳遞數組。」 – haju 2012-08-14 20:00:19

+0

我不明白,它在我的環境中工作。這也是:「when(mockedClassB.getResult(any(String []。class)))。thenReturn(someValue);」 – gontard 2012-08-14 20:17:17

+0

我完成了我的答案,請提供一些關於你的環境的細節:junit,powermock,powermockito和mockito版本,還提供了ClassATest#mockingTest中someValue的值 – gontard 2012-08-15 06:28:25