繁体   English   中英

PowerMockito:模拟私有方法并获得值而不访问它

[英]PowerMockito: mocking private method and get a value without accessing it

我正在为遗留代码编写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());
 }

}

我尝试使用PowerMockito做到这一点,但没有成功。 可以使用PowerMockito?模拟这种情况。

您可以使用PowerMockito间谍:

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

    private int getMode() {
        return 5;
    }
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM