Skip to content
Advertisement

How to mock local object property which is been set in another method

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement