如何使用Mockito模拟构造函数对象属性?

时间:2019-12-15 04:20:54

标签: java mockito

我正在尝试在测试类中模拟构造函数“ EmailParams”。 由于构造函数EmailParams模拟为null,因此模拟失败。

下面是我的测试方法

@Test
   public void getContactEmailsByFilterSuccessTest() throws Exception {

    String contactId = "752";
    String emailAddress = "test@gmail.com";
    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("test@gmail.com", "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());   
 }

这是我尝试模仿的方法。尝试模拟构造函数时测试失败

@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;
}

这是我的具有构造函数的类。

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;
    }
}

如何正确模拟它?预先感谢。

2 个答案:

答案 0 :(得分:2)

如果默认情况下equals类中的EmailParams方法没有被覆盖,Mockito使用Object.equals比较传递给EmailParams方法的getEmailByFilter 。在您的情况下,两个对象属性都具有相同的值,但它们仍然是不同的对象。因此,要么覆盖equals中的EmailParams方法,要么 使用ArgumentMatchers.argThat

 when(emailServiceMock.getEmailByFilter(ArgumentMatchers.argThat(p -> p.getPEmail().equals("test@gmail.com") && condition2 && condition3 )))
                  .thenReturn(emailsList);

答案 1 :(得分:0)

因此,emailService应该与emailParams一起调用。 emailParams使用emailAddressemailTypecontactId构造。如果仔细观察,您会发现控制器中的sourcedContactscontXrefService.getContactsForId(contactId)的结果。

为什么这是个问题?好吧,在测试中看看这一行:

when(contactXrefServiceMock.getContactsForEcmId(contactId)).thenReturn(sourcedContacts)

您正在嘲笑getContactsForEcmId以返回sourcedContacts。相反,您应该嘲笑getContactsForId