I am pretty new to Mockito and Junit 5.
I am trying to mock out the Config class’s getNumber() method so that it returns -1.
Here is a basic outline:
The class I need to mock:
class Config {
private final int number;
Config(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
The unit under test is the MyService constructor:
class MyService {
private final Config config;
MyService(Config config) {
if(config.getNumber() < 0) {
throw new IllegalStateException("Number cannot be less than 1!");
}
this.config = config;
}
}
I want to test the MyService constructor when I pass it a mock Config object.
But it needs access to the getNumber() method (which I need to set the return value for).
However, since the MyService number field is private final, getNumber() returns 0 instead of -1.
My test code:
@Test
void MyService_construct() {
Config mockConfig = Mockito.mock(Config.class);
Mockito.when(mockConfig.getNumber()).thenReturn(-1);
Field numberField = Config.class.getDeclaredField("number");
numberField.setAccessible(true);
numberField.set(mockConfig, -1);
assertThrows(Exception.class, () -> MyService(mockConfig));
}
How can I mock out the behavior of Config.getNumber() such that it returns -1? Keep in mind that the number private final field is normally set in the constructor by reading a file – hence the problem with mocking the class.