[英]Partial Mock Private Method with PowerMock-Mockito
我是Mockito和PowerMock的新手。 我需要測試一些遺留代碼,它有一個我必須模擬的私有方法。 我正在考慮使用PowerMock的私有部分模擬功能,我試圖模仿鏈接中的示例,但它失敗了。 我不知道它有什么問題。 你能幫忙檢查一下嗎? 謝謝
這是待測試的類:
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());
我發現了問題,測試方法需要一個例外。 我修改它如下后,它工作正常。
@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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.