Issue
I here have a simplified version of my problem. Class A has a protected method. Class B inherits this method.
public class A{
protected String getString(){
//some Code
}
}
public class B extends A{
public void doSomething(){
//someCode
String result = getString();
}
}
I now write a Unit-Test with Mockito, which is in another package-test and I want to test the doSomething()
method. To do that, I need to mock the getString()-call. Since the method is protected and my test-class is in a differnet package, I can't use doReturn(...).when(classUnderTest).getString()
. The thing is, that I spy on class B. So I can't use mock(new B(), Mockito.CALLS_REAL_METHODS)
.
I tried getting the protected method via Reflection:
Method getString = classUnderTest.getClass().getDeclaredMethod("getString");
getString.setAccessible(true);
But I then don't know how to use this inside doReturn()
.
Solution
You can use 'override and subclass'
B b = new B() {
@Override
protected String getString() {
return "FAKE VALUE FOR TESTING PURPOSES";
};
};
Answered By - KarlM
Answer Checked By - Marilyn (JavaFixing Volunteer)