使用PowerMock-Mockito的部分模拟私有方法

时间:2013-07-18 20:27:56

标签: java junit mockito powermock private-methods

我是Mockito和PowerMock的新手。我需要测试一些遗留代码,它有一个我必须模拟的私有方法。我正在考虑使用PowerMock的私有部分模拟功能,我试图模仿link中的示例,但它失败了。我不知道它有什么问题。你能帮忙检查一下吗?感谢

这是待测试的课程:

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());

1 个答案:

答案 0 :(得分:4)

我发现了问题,测试方法需要一个例外。我按如下方式对其进行修改后,工作正常。

@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());

   }

}