2013-07-18 37 views
0

我是Mockito和PowerMock的新手。我需要測試一些具有私有方法的遺留代碼,我不得不嘲笑它。我正在考慮使用PowerMock中的私人部分模擬功能,我試圖模仿link中的示例,但它失敗了。我不知道它有什麼問題。你能幫忙檢查一下嗎?由於部分模擬使用PowerMock-Mockito的私人方法

這裏的類待測試:

package test; 

public class ClassWithPrivate 
{ 

    private String getPrivateString() { 
     return "PrivateString"; 
    } 

    private String getPrivateStringWithArg(String s) { 
     return "PrivateStringWithArg"; 
    } 

} 

,這是測試代碼:

package test; 

import static org.mockito.Mockito.*; 
import static org.mockito.Matchers.anyString; 
import static org.powermock.api.mockito.PowerMockito.when; 
import static org.powermock.api.support.membermodification.MemberMatcher.method; 

import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.mockito.invocation.InvocationOnMock; 
import org.mockito.stubbing.Answer; 
import org.powermock.api.mockito.PowerMockito; 
import org.powermock.core.classloader.annotations.PrepareForTest; 
import org.powermock.api.support.membermodification.MemberMatcher; 
import org.powermock.modules.junit4.PowerMockRunner; 

@RunWith(PowerMockRunner.class) 
@PrepareForTest(ClassWithPrivate.class) 
public class ClassWithPrivateTest { 

    @Test 
    public void testGetPrivateString() { 

     ClassWithPrivate spy = PowerMockito.spy(new ClassWithPrivate()); 

     PowerMockito.doReturn("Do").when(spy, method(ClassWithPrivate.class, "getPrivateStringWithArg", String.class)).withArguments(anyString()); 

    } 

} 

編輯 當我試圖編譯的代碼,它因以下錯誤而失敗:

ClassWithPrivateTest.java:26: unreported exception java.lang.Exception; must be caught or declared to be thrown 
    PowerMockito.doReturn("Do").when(spy, method(ClassWithPrivate.class, "getPrivateStringWithArg", String.class)).withArguments(anyString()); 
            ^
ClassWithPrivateTest.java:26: unreported exception java.lang.Exception; must be caught or declared to be thrown 
    PowerMockito.doReturn("Do").when(spy, method(ClassWithPrivate.class, "getPrivateStringWithArg", String.class)).withArguments(anyString()); 
+0

對我來說,測試按預期工作。 「失敗」是什麼意思?運行測試時是否有例外?然後張貼在這裏。 –

+0

@ChristopherRoscoe:嗨,當我編譯它時,它給了我上面的錯誤。你編譯成功了嗎?謝謝 – thirty

回答

3

我發現了這個問題,測試方法期望有一個例外。我修改後如下,它工作正常。

@RunWith(PowerMockRunner.class) 
@PrepareForTest(ClassWithPrivate.class) 
public class ClassWithPrivateTest { 

    @Test 
    public void testGetPrivateString() throws Exception { 

    ClassWithPrivate spy = PowerMockito.spy(new ClassWithPrivate()); 

    PowerMockito.doReturn("Do").when(spy, method(ClassWithPrivate.class, "getPrivateStringWithArg", String.class)).withArguments(anyString()); 

    } 

}