I'm new to MockMVC and junit stuffs so need a help ,so the situation is I need to mock a method while mocking the outer method which contains the method. For example method calculator(int a , int b) , i mock this method with two mock values, and within this method there is another method which does some other validations (lets say some external validations) .
I'm able to mock the main method calculator till the point where this external method is being called, i used to "Given().willReturn()" to mock the main method (calculator), and another "Given().willReturn()" statement to mock the containing method(validations one), but that gives me nullPointer exception. So I need something that could help me with this, so that the mocking can be done in an orderly fashion.
public GuestRegistrationResponse registerGuest(SomeObject guestRegistrationRequest) throws Exception {
SomeObject guestRegistrationResponse = new SomeObject();
Folio folio = new Folio();
folio.setForename(guestRegistrationRequest.getForename());
folio.setEmail1(guestRegistrationRequest.getEmail());
folio.setCity(guestRegistrationRequest.getCity());
Result result = null;
result = (Result) sampleAPICall.executeExternalAPI(result,new Class[] { SomeObject.class, User.class, Another.class, Folio.class, FolioList.class },
Result.class);
if (result != null && result.getFolioList() != null ) {
guestRegistrationResponse.setFolioid(result.getFolioList().getFolio().getFolioId());
} else {
throw new ExternalException(result.getResult());
}
return guestRegistrationResponse;
}
Test method
@RunWith(SpringRunner.class)
@WebMvcTest(value = ServiceImpl.class, secure = true)
public class TestServiceImpl {
@Autowired
MockMvc mockmvc;
@InjectMocks
ServiceImpl serviceImpl;
@Before
public void setUp() {
// We would need this line if we would not use MockitoJUnitRunner
MockitoAnnotations.initMocks(this);
// Initializes the JacksonTester
JacksonTester.initFields(this, new ObjectMapper());
}
@Test
public void testRegisterGuest() throws Exception {
SomeObject mockInput = new SomeObject();
mockInput.setCity("CITY");
mockInput.setEmail("test@test.com");
mockInput.setForename("FORENAME");
/* other datat is also collected*/
ExpectedResponse mockOutput = new ExpectedResponse();
mockOutput.setResult(true);
Result Result = new Result();
Result.setMessage("success");
Result.setStatus(true);
processTestThatMethod(mockInput, mockOutput, Result);
}
private void processTestThatMethod(SomeObject mockInput, ExpectedResponse mockOutput,
,Result result) throws Exception {
System.out.println("Inside processTestThatMethod");
given(serviceImpl.registerGuest(mockInput)).willReturn(mockOutput);
// what to do below ..
given(sampleAPICall.executeExternalAPI(any(Result.class),any(new Class[]{SomeObject.class, User.class, Another.class, Folio.class, FolioList.class}),any(Result.class))).willReturn(result);
}
}
Have edited the code @Sachin rai