1

I have similar to below code in my application.

public String someMethod(final Object obj) {
    final ValidationResponse validationResponse = new ValidationResponse();
    String responseMessage = validatorService.validate(obj, validationResponse);
    if(validationResponse.isValid()) {
        //Positive flow
    }
    else {
        //Negative flow
    }
    return responseMessage;
}

I am writing JUnit test cases to generate Mutation's report. As the object validationResponse is used which is a local object created in the flow. Mockito is unable to get & return desired value for isValid. Due to this I am unable to cover the test cases for the Positive flow.

How this could be achieved? Any lead is very much appreciated.

mevada.yogesh
  • 1,118
  • 3
  • 12
  • 35

2 Answers2

1

I got the solution to this problem from one of my teammate. It is as below

Mockito.doNothing(invocation ->
{
    ValidationResponse validationResponse = invocation.getArgument(0);
    validationResponse.setValida(true);//Set value true or false based on the mock test case scenario.
    return null;
})
.when(validatorService)
.validate(obj, validationResponse));

This mocks the value of the validation response property.

mevada.yogesh
  • 1,118
  • 3
  • 12
  • 35
0

The flow of this method is determined by this line

 String response = validator1.validate(obj, validationResponse);

If you want to excercise both branches of the following if statment you need to control the modification that validator1 makes to the validationResponse object.

This can be done in two ways.

If your test can inject the instance of validator1 (eg via the code under tests constructor) then you can fake it.

This is probably easiest to do with a hand coded implementation rather than a mocking framework.

eg

class AlwaysInvalid implements WhateverTheTypeOfValidator1Is {
    void validate(Object unused, ValidationResponse response) {
       response.setInvalidOrWhatever();
    }
}

Alternatively you can use a real collaborator, in which case your tests needs to ensure that objects are passed into someMethod that result in both valid and invalid responses.

henry
  • 5,923
  • 29
  • 46