模拟继承的受保护方法

use*_*542 6 java junit unit-testing mockito

我这里有我的问题的简化版本。A类有一个受保护的方法。B类继承了这个方法。

public class A{
    protected String getString(){
        //some Code
    }
}


public class B extends A{
    public void doSomething(){
        //someCode
        String result = getString();
    }
}
Run Code Online (Sandbox Code Playgroud)

我现在用 Mockito 编写一个单元测试,它位于另一个包测试中,我想测试该doSomething()方法。为此,我需要模拟 getString() 调用。由于该方法受到保护并且我的测试类位于不同的包中,因此我无法使用doReturn(...).when(classUnderTest).getString(). 问题是,我监视 B 类。所以我不能使用mock(new B(), Mockito.CALLS_REAL_METHODS).

我尝试通过反射获取受保护的方法:

Method getString = classUnderTest.getClass().getDeclaredMethod("getString");
getString.setAccessible(true);
Run Code Online (Sandbox Code Playgroud)

但我不知道如何在里面使用它doReturn()

Kar*_*rlM 4

您可以使用“覆盖和子类”

B b = new B() {
  @Override
  protected String getString() {
    return "FAKE VALUE FOR TESTING PURPOSES";
  };
};
Run Code Online (Sandbox Code Playgroud)