I am new to JUnit and Mockito, and am struggling trying to mock a value coming back from a boolean method to hit inside a conditional.
I have tried the answer from this post, but doesn't seem to work for this. I’ve tried using spy, thenCallRealMethod, can’t figure it out.
I have tested for when the value is true, but I cannot seem to get inside the else part for the test.
Here an example of what I've done:
ServiceImpl.java has a method register() that calls a boolean method shouldRegister(). The shouldRegister() method simply checks another service to see if a boolean value is true or false, and then returns that.
If true, it builds a JsonNode payload to send, else, if false, it removes one field from the payload.
// ServiceImpl.java:
// in the record() method:
if (body.has("fieldtoBeRemoved")) {
if (shouldRegister()) {
((ObjectNode) body).set("fieldtoBeRemoved");
} else {
// this is the line I am trying to test
((ObjectNode) body).remove("fieldtoBeRemoved");
}
}
// method being called above in the conditional
protected boolean shouldRegister() {
Optional<String> flag = configService.getString("booleanValue");
String stringFlag = flag.orElse("false");
return BooleanUtils.toBoolean(stringFlag);
}
// In the test
@InjectMocks
private ServiceImpl serviceImpl;
@Test
public void testingForFalse() {
serviceImpl = new ServiceImpl();
// what I am struggling with, trying to make the value false,
// so that it hits the else in the record() method in ServiceImpl
// and removes fieldtoBeRemoved from the payload
when(serviceImpl.shouldRegister()).thenCallRealMethod();
doReturn(false).when(spy(serviceImpl)).shouldRegister();
assertThat(fieldtoBeRemoved, is(""));
}
When I run this, it fails because the value of fieldtoBeRemoved is not empty, it has the value from the field in the payload, which it should not have. I’m guessing the value is still coming back as true because I’m not mocking it correctly/setting it to be false for this test case. I’ve also tried mocking the call to the record() method. Any help appreciated!