PowerMockito中的doAnswer()无法正常工作

时间:2017-11-08 08:51:06

标签: unit-testing junit mockito powermockito

这里我尝试在调用create()方法内的createContact()方法并使用create()参数模拟anySting()方法时返回null。但每当我调用此方法时,它都会返回InvalidDataException,尽管我用anyString()嘲笑了

以下是我的@Test方法来测试createContact方法

@Test
   public void testCreateContact() throws Exception{
       Contact contact = new Contact();    
       ContactHelper mockObj = PowerMockito.mock(Helper.class);
       PowerMockito.whenNew(Helper.class).withAnyArguments().thenReturn(mockObj);
       doAnswer(new Answer<Void>() {
            public Void answer(InvocationOnMock invocation) {
                return null;
            }
            }).when(spy).createContact(anyString(),(Contact)anyObject(),anyString());
       doAnswer(new Answer<Void>() {
            public Void answer(InvocationOnMock invocation) {
                return null;
            }
            }).when(mockObj).create(anyString(),anyString(),(Contact)anyObject());

       obj.createContact("realmId", contact, appId);
   }

以下是我的createContact方法,

public void createContact(String id, Contact contact, String uid) throws CareException{
        Helper helper = new Helper();
        try {
            helper.create(id, uid, contact);
        } catch (CareException ex) {
            if(!contact.isDeleted() && contact.isAccountCreateOnFailureEnabled() && ex.getMessage().matches("Code=Account")){
                handlemethod(id, contact, uid);
                return;
            }
            throw ex;
        }
    }

有些情况下,我手动投掷careException,即使是我得到的同事invalidDataException

0 个答案:

没有答案