'Test mocked private method
The test for the public method getA() works as expected, but the test for the private method getB() does not return the mocked value "b", but "B", which corresponds to the actual return value of the method getB(). How must the test to getB() be adjusted so that the mocked value "b" is returned?
public class Letters {
public String getA() {
return "A";
}
private String getB() {
return "B";
}
}
class LettersTest {
Letters mockedLetters = mock(Letters.class);
@Test
void getA() {
when(mockedLetters.getA()).thenReturn("a");
assertThat(mockedLetters.getA()).isEqualTo("a"); // True.
// To check if ReflectionTestUtils actually sets the value in mockedLetters.
when(ReflectionTestUtils.invokeMethod(mockedLetters, "getA")).thenReturn("aa");
assertThat(mockedLetters.getA()).isEqualTo("aa"); // True.
}
@Test
void getB() {
when(ReflectionTestUtils.invokeMethod(mockedLetters, "getB")).thenReturn("b");
assertThat((String)ReflectionTestUtils.invokeMethod(mockedLetters, "getB")).isEqualTo("b"); // False; expected: "b", but was: "B".
}
}
Solution 1:[1]
You can do:
- Using PowerMockito
- Using Reflection to change your private method to public one for test and change it back.
But... wait... Don't ever do any of above things. Because:
- You need to design your code to be testable.
- Private methods should be tested through the public ones. Read more about TDD.
Some references I can see for you:
you shouldn't test private methods directly, but only their effects on the public methods that call them
- Learn from previous post
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nnhthuan |
