有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    错误消息是不言自明的

    The method methodToBeMocked() from the type MyClass is not visible

    该方法不可见的原因是因为它是private方法。私有方法只能在其定义的类内调用。如果希望从任何地方都可以访问该方法,请将该方法设置为public

    public String methodToBeMocked() { // Need to mock return value
        return "Default";
      }
    

    Information about method access specifiers