2016-01-13 60 views
0

我有一個文件Util.java存根靜態方法調用:無法使用PowerMockito

public class Util { 
    public static int returnInt() { 
     return 1; 
    } 

    public static String returnString() { 
     return "string"; 
    } 
} 

另一類:

public class ClassToTest { 
    public String methodToTest() { 
     return Util.returnString(); 
    } 
} 

我希望它用TestNG和PowerMockito測試:

@RunWith(PowerMockRunner.class) 
@PrepareForTest(Util.class) 
public class PharmacyConstantsTest {  
    ClassToTest classToTestSpy; 

    @BeforeMethod 
    public void beforeMethod() { 
     classToTestSpy = spy(new ClassToTest()); 
    } 

    @Test 
    public void method() throws Exception { 
     mockStatic(Util.class); 
     when(Util.returnString()).thenReturn("xyz"); 
     classToTestSpy.methodToTest(); 
    } 
} 

但是,它會拋出以下錯誤:

FAILED: method org.mockito.exceptions.misusing.MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'. For example: when(mock.getArticles()).thenReturn(articles);

我試過這個解決方案,使用來自網絡的各種解決方案,但無法找到我的代碼中的錯誤。我需要將靜態方法的調用存根,因爲我需要它用於傳統代碼。 How do I mock a static method using PowerMockito?

+0

我也試過這些。無效: 1.'PowerMockito.when(Util.class,MemberMatcher.method(Util.class,「returnString」))。withNoArguments()。thenReturn(「xyz」);' 2.'PowerMockito.doReturn(「 (Util.class,「returnString」);' 3.'doReturn(「xyz」)。when(Util.class); \t Util.returnString();' – Caesar

回答

0

只是爲了記錄在案,加入使得測試類的PowerMockTestCase一個子類爲我工作。

@PrepareForTest(Util.class) 
public class PharmacyConstantsTest extends PowerMockTestCase {  
    ClassToTest classToTestSpy; 

    @BeforeMethod 
    public void beforeMethod() { 
     classToTestSpy = spy(new ClassToTest()); 
    } 

    @Test 
    public void method() throws Exception { 
     mockStatic(Util.class); 
     when(Util.returnString()).thenReturn("xyz"); 
     classToTestSpy.methodToTest(); 
    } 
} 
1

您需要TestNG的配置爲使用PowerMock對象工廠是這樣的:

<suite name="dgf" verbose="10" object-factory="org.powermock.modules.testng.PowerMockObjectFactory"> 
    <test name="dgf"> 
     <classes> 
      <class name="com.mycompany.Test1"/> 
      <class name="com.mycompany.Test2"/> 
     </classes> 
    </test> 
</suite> 

在項目的suite.xml文件。請致電link

+0

我的項目中沒有'suite.xml'。但我有一個'testng.xml'文件,其中包含一些內容。那麼應該創建一個'suite.xml',如果是的話,它的路徑是什麼? – Caesar

+0

是的,在同一個'testng.xml'文件中,您需要使用** org.powermock.modules.testng.PowerMockObjectFactory **指定要測試的類。無論如何,我看到你已經發現如何以編程方式做到這一點。 –

+0

如果沒有'extends PowerMockTestCase',上面的解決方案對我不起作用。 – Caesar

0

使用PowerMockito方法而不是Mockito's。該文檔指出:

PowerMockito extends Mockito functionality with several new features such as mocking static and private methods and more. Use PowerMock instead of Mockito where applicable.

每個實例:

PowerMockito.when(Util.returnString()).thenReturn("xyz"); 
+0

我改變了以下測試方法。它仍然顯示相同的錯誤:@Test public void method(){ \t \t PowerMockito.mockStatic(Util.class); PowerMockito.when(Util.returnString())。thenReturn(「xyz」); \t classToTestSpy.methodToTest(); } – Caesar

相關問題