How to test my service class which has storeInDb()
method and is returning database model and httpstatus.OK
and httpstatus.Bad_Request
along with body.
public ResponseEntity storeInDb(ExeEntity model) {
Validator validation = new Validator();
Map objValidate = validation.validateInput(model.getLink(), model.getUsername(), model.getPassword(),
model.getSolution(), model.getDomain());
if (objValidate.containsKey("Success")) {
return new ResponseEntity(model, HttpStatus.OK);
}
else if (objValidate.containsKey("Fail")) {
if (objValidate.containsValue("Invalid Credentials")) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid Credentials");
} }
else {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Domain does not exist.");
}
}
Please help me answering this question and writing test cases. Thanks in advance.
With the current design of your code a Unit Test is really hard.
The complete logic of your method is based on the result of the ExeEntityValidator
. In other words it is dependent on it. Such dependencies should be mocked away in a Unit Test.
In order to mock this validator you should apply a dependency injection. This means you provide the dependency instead of creating it yourself in the place it is needed. This is done by passing the dependency into the constructor of your class and store it as member variable.
If you do this your test code could look something like this:
void test(){
// mock a ExeEntityValidator that is used inside your '::storeInDb' method
Map<String, Object> objValidated = Map.of("Success", true);
var validator = mock(ExeEntityValidator);
doReturn(objValidated).when(validator).validateInput(any(ExeEntity.class));
// instantiate your component with the mocked ExeEntityValidator
var cut = new UnknownClass(validator);
var model = new ExeEntity(...);
// call the method you want to test
var response = cut.storeInDb(model);
assertEquals(HttpStatus.OK, response.getStatusCode());
}