PowerMockito:模拟私有方法并在不访问它的情况下获取值

Mad*_*ith 0 java unit-testing mocking mockito powermock

我正在为遗留代码编写java单元测试,我也是这个领域的新手.我必须测试以下场景(写单元测试用例testableMethod()).因此,如果不在getMode()方法中执行代码,我想获得mode变量的值.

Class A{

 public boolean testableMethod()
 {
   //code
   ......
   int mode = getMode();
   ......
   //do something with mode
   return X;
 }

 private int getMode()
 {
   return ComplexCalls(ComplexMethodCalls(), more());
 }

}
Run Code Online (Sandbox Code Playgroud)

我试图使用PowerMockito这样做而没有取得成功.可以用PowerMockito来模拟这种场景吗?

gon*_*ard 7

你可以和PowerMockito间谍一起:

public class A {
    public boolean testableMethod() {
        return getMode() == 1;
    }

    private int getMode() {
        return 5;
    }
}
Run Code Online (Sandbox Code Playgroud)
import static org.junit.Assert.assertTrue;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import static org.powermock.api.mockito.PowerMockito.spy;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest(A.class)
public class ATest {
    @Test
    public void testableMethod_should_do_this() throws Exception {
        A a = spy(new A());

        doReturn(1).when(a, "getMode");

        assertTrue(a.testableMethod());
    }
}
Run Code Online (Sandbox Code Playgroud)

查看私有方法的部分模拟的所有完整示例