在这种情况下,为什么 Mockito doThrow 不抛出异常?与模拟零交互

Why isnt Mockito doThrow throwing an Exception in this case? zero interactions with mock

我正在测试的方法(方法 setEventHubDataPayload 抛出 JSONException 和 JsonProcessingException):

public class EventHubMapper {

//inits

public byte[] toEventDataJsonByteArray(UserRecord inbound) {
    EventHubDto ehDto = new EventHubDto();

    ehDto.setEventTypeVersion(inbound.getVersion());
    ehDto.setEventId(inbound.getNotificationId());

    JSONObject eventJson = new JSONObject(ehDto);

    try {
        eventJson.put("data", setEventHubDataPayload(ehDto, inbound));
    } catch (JSONException e) {
        analytics.trackError(AnalyticsConstants.EventHub.JSON_MAPPING_ERROR, e.toString());
    } catch (JsonProcessingException e) {
        analytics.trackError(AnalyticsConstants.EventHub.JSON_PROCESSING_ERROR, e.toString());
    }

    return eventJson.toString().getBytes();
}

}

单元测试代码:

 @Test
public void toEventDataByteArray_JsonException() throws JSONException, JsonProcessingException {
    EventHubMapper ehmMock = Mockito.spy(eventHubMapper);

    doThrow(new JSONException("blah")).when(ehmMock).setEventHubDataPayload(any(), any());

    eventHubMapper.toEventDataJsonByteArray(setUpMockUserRecord());

    verify(analytics, times(1)).trackError( AnalyticsConstants.EventHub.JSON_MAPPING_ERROR, new JSONException("blah").toString());

}

我试过使用更具体的匹配器...例如:any(EventHubDto.class) 或 any(UserRecord.class) 并得到相同的结果:

Wanted but not invoked:
analytics.trackError(
"EventHub_Publish_Error",
""
;

还有

Actually, there were zero interactions with this mock. 

这是怎么回事?

我认为您在测试时需要像下面这样调用。

   ehmMock.toEventDataJsonByteArray(setUpMockUserRecord());