java模拟已标记为可访问的私有方法的返回值
我的单元测试:
@Test
public void testDoSomething() {
Method m = MyClass.class.getDeclaredMethod("methodToBeMocked");
m.setAccessible(true);
MyClass myClass = spy(new MyClass());
//m.invoke(myClass); // Calling this invokes the private method correctly
when(myClass.methodToBeMocked()).thenReturn("DummyReturn"); // This line throws the compiler error
myClass.doSomething(); // This is the method I'm trying to test
}
这是我得到的编译器错误:
The method methodToBeMocked() from the type MyClass is not visible
这是MyClass
public MyClass {
public MyClass() {}
public void doSomething() {
..
methodToBeMocked();
..
}
private String methodToBeMocked() { // Need to mock return value
return "Default";
}
}
# 1 楼答案
错误消息是不言自明的
该方法不可见的原因是因为它是
private
方法。私有方法只能在其定义的类内调用。如果希望从任何地方都可以访问该方法,请将该方法设置为public
Information about method access specifiers