I am using Spring Boot 2.2.4.RELEASE
.
I have this piece of code in my controller, where i am using the "free" DataSourceHealthIndicator
to check if the DB is DOWN:
@Autowired
private DataSourceHealthIndicator d;
//some code
if("DOWN".equals(d.getHealth(false).getStatus().getCode())) {
// do something
} else {
// proceed
}
Now, in my slice test, i would like to mock it(the DataSourceHealthIndicator
), but i have a null pointer, as obviously getHealth() is not returning a Health object, getStatus() is not returning a Status object...
@WebMvcTest
//some code
@MockBean
private DataSourceHealthIndicator d;
//some code
given(this.d.getHealth(anyBoolean()).getStatus().getCode()).willReturn("UP");
How can i go about mocking it?
I tried this:
given(this.d.getHealth(anyBoolean())).willReturn(Health.up().build());
given(this.d.getHealth(anyBoolean()).getStatus()).willReturn(Status.UP);
given(this.d.getHealth(anyBoolean()).getStatus().getCode()).willReturn("UP");
But it is failing on the 2nd given statement:
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
Status cannot be returned by getHealth()
getHealth() should return Health
I shifted the DataSourceHealthIndicator code to a class of its own.
This has allowed me to easily slice test the Controller layer and at the same time it has allowed me to easily test the other class, with just the MockitoExtension.class
.
SRP & KISS principle in action.