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()
.
You can use 'override and subclass'
B b = new B() {
@Override
protected String getString() {
return "FAKE VALUE FOR TESTING PURPOSES";
};
};
There might be a cleaner way of doing this, but here goes...
For example...
private A partialMock;
private B classUnderTest;
@Before
public void setup() {
partialMock = mock(A.class);
classUnderTest = new B() {
@Override
protected String getString() {
return partialMock.getString();
}
};
}
@Test
public void shouldDoSomething() {
when(partialMock.toString()).thenReturn("[THE MOCKED RESPONSE]");
classUnderTest.doSomething();
// ...verify stuff...
}
Obviously you don't even need to use mocking, you can just return something directly from the overridden method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With