How to mock a constructor object properties using Mockito?

user3919727 :

I am trying to mock a constructor 'EmailParams' in my test class. Mocking is failing since the constructor EmailParams mocks as null.

Below is my test method

@Test
   public void getContactEmailsByFilterSuccessTest() throws Exception {

    String contactId = "752";
    String emailAddress = "[email protected]";
    String emailType = "EW";

    MockHttpServletRequest request = new MockHttpServletRequest();
    when(helper.isNumeric(any(String.class))).thenReturn(true);

    List<ContactXref> sourcedContacts = getContactXrefs();
    when(contactXrefServiceMock.getContactsForId(contactId)).thenReturn(sourcedContacts);

    EmailParams emailParams = new EmailParams("[email protected]", "EW", sourcedContacts.get(0).getContact().getContactId().toString());

    List<Email> emailsList = getEmailsList();
    when(emailServiceMock.getEmailByFilter(emailParams)).thenReturn(emailsList);

    ResponseEntity<List<Email>> response = contactControllerMock.getContactEmailsByFilter(request, contactId, emailAddress, emailType);
    Assert.assertEquals("getContactEmailsByFilterSuccessTest: Expected response code to be 200", "200", 
  response.getStatusCode().toString());   
 }

This is the method I am trying to mock. Test fails when its trying to mock the constructor

@GetMapping(value = "/{contactId}/" + UrlMapping.EMAILS, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Email>> getContactEmailsByFilter(HttpServletRequest request,
                                                            @PathVariable(name = RequestParams.CONTACTID) String contacId,
                                                            @RequestParam(required = false, name = RequestParams.EMAILADDRESS) String emailAddress,
                                                            @RequestParam(required = false, name = RequestParams.EMAILTYPE) String emailType)
                                                            throws Exception {


      ResponseEntity response = new ResponseEntity("Only numeric contactId is allowed", HttpStatus.BAD_REQUEST);

      List<Email> emailList;
      List<ContactXref> sourcedContacts;

      if (helper.isNumeric(contactId)) {

          sourcedContacts = contXrefService.getContactsForId(contactId);

          EmailParams params = new EmailParams(emailAddress, emailType, sourcedContacts.get(0).getContact().getContactId().toString());

          emailList = emailService.getEmailByFilter(params);
          if (emailList != null) {
               response = emailList.size() == 0 ? new ResponseEntity("No emails were found for the request", HttpStatus.NOT_FOUND) : new ResponseEntity(emailList, new HttpHeaders(), HttpStatus.OK);
           } else {
              response = new ResponseEntity("Encountered exception in retrieving emails", HttpStatus.INTERNAL_SERVER_ERROR);
          }
      }
       return response;
}

Here is my class which has the constructor.

public class EmailParams {

    String email;
    String emailType;
    String ptyId;

    public EmailParams() {
        super();
    }

    public EmailParams(String pEmail, String pEmailType, String pPtyId) {
        email = pEmail;
        emailType = pEmailType;
        ptyId = pPtyId;
    }
}

How to mock it properly? thanks in advance.

Deadpool :

If the equals method is not overridden in EmailParams class by default Mockito uses Object.equals to compare the EmailParams passed to getEmailByFilter method. In your case both object properties have same values but still they are different objects. So either override the equals method in EmailParams or use ArgumentMatchers.argThat

 when(emailServiceMock.getEmailByFilter(ArgumentMatchers.argThat(p -> p.getPEmail().equals("[email protected]") && condition2 && condition3 )))
                  .thenReturn(emailsList);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=358911&siteId=1
Recommended