最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

java - Mockito not able to catch the exception thrown - Stack Overflow

programmeradmin6浏览0评论

I'm trying to write a test for failure scenario where I'm trying to catch an exception but all I'm receiving is AssertionError

This is the exception I received.I've tried catching JsonProcessingException.

If you have any suggestion to have better debug this I'm all ears?

 exception: comfoo.BarService.order.service.exception.ErrorJsonProcessingException
java.lang.AssertionError: Expected exception: comfoo.BarService.order.service.exception.ErrorJsonProcessingException

Test class is as follows:

@Test(expected = ErrorJsonProcessingException.class)
public void testEmailOnBar_JsonProcessingException() throws Exception {
        // Given
  EmailOnBarRequest request = new EmailOnBarRequest();
  HttpHeaders httpHeaders = getHttpHeaders();
       when(BarServiceServiceConfig.getEmailOnBarUrl()).thenReturn("bar/rp-webapp-9-common/ecommerce/wireless/order/emailOnBar?lo=%s&sc=%s");

  BarResponse BarResponse = new BarResponse();
  BarResponse.setMessage("testValue");

  when(barServiceConnector.getBipbarResponse(anyString(), any(HttpEntity.class), any(HttpHeaders.class), any(HttpMethod.class))).thenReturn(BarResponse);
  when(mapper.readValue(anyString(), eq(ImplEmailOnBarOutput.class))).thenThrow(new JsonProcessingException("test") {});

  // When
  orderProcessor.emailOnBar(request, httpHeaders, "salesChannel", "lo");

    }

SUT


@InjectMocks
private OrderProcessor orderProcessor;

@Mock
private barServiceConnector barServiceConnector;

@Mock
private BarServiceServiceConfig BarServiceServiceConfig;

@Mock
private ObjectMapper mapper;

@Mock
private ObjectWriter objectWriter;

@Autowired
private barServiceConnector barServiceConnector;

@Autowired
private BarServiceServiceConfig BarServiceServiceConfig;

@Autowired
private static ObjectMapper mapper;

@Autowired
private static ObjectWriter objectWriter;

static {
    if (mapper == null)
        mapper = new ObjectMapper();
    if (objectWriter == null)
        objectWriter = mapper.writer().withDefaultPrettyPrinter();
}

public ImplEmailOnBarOutput emailOnBar(EmailOnBarRequest input, HttpHeaders httpHeaders, String sc, String lo) {
    try {
        LOGGER.debug("Entering emailOnBar method with input: {}, lo: {}, salesChannel: {}", objectWriter.writeValueAsString(input), lo, sc);

        String url = String.format(BarServiceServiceConfig.getEmailOnBarUrl(), lo, sc);
        LOGGER.debug("Calling bar API with URI: {}", url);

        BarResponse BarResponse = barServiceConnector.getOrgbarResponse(url, new HttpEntity<>(input), httpHeaders, HttpMethod.POST);     mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(objectWriter.writeValueAsString(BarResponse), ImplEmailOnBarOutput.class);
    } catch (JsonProcessingException e) {
        LOGGER.error("Exception while calling bar-emailOnBar api exception={}", e);
        throw new ErrorJsonProcessingException(e, JSON_PROCESSEING_ERROR_MSG, bar_SERVICE);
    }
}

POJO

@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ImplEmailOnBarOutput {
    @JsonProperty("__EmptyObject__")
    private EmptyObject emptyObject;
}

@Data
@NoArgsConstructor
@JsonSerialize
public class EmptyObject {

}

I'm trying to write a test for failure scenario where I'm trying to catch an exception but all I'm receiving is AssertionError

This is the exception I received.I've tried catching JsonProcessingException.

If you have any suggestion to have better debug this I'm all ears?

 exception: com.foo.BarService.order.service.exception.ErrorJsonProcessingException
java.lang.AssertionError: Expected exception: com.foo.BarService.order.service.exception.ErrorJsonProcessingException

Test class is as follows:

@Test(expected = ErrorJsonProcessingException.class)
public void testEmailOnBar_JsonProcessingException() throws Exception {
        // Given
  EmailOnBarRequest request = new EmailOnBarRequest();
  HttpHeaders httpHeaders = getHttpHeaders();
       when(BarServiceServiceConfig.getEmailOnBarUrl()).thenReturn("bar/rp-webapp-9-common/ecommerce/wireless/order/emailOnBar?lo=%s&sc=%s");

  BarResponse BarResponse = new BarResponse();
  BarResponse.setMessage("testValue");

  when(barServiceConnector.getBipbarResponse(anyString(), any(HttpEntity.class), any(HttpHeaders.class), any(HttpMethod.class))).thenReturn(BarResponse);
  when(mapper.readValue(anyString(), eq(ImplEmailOnBarOutput.class))).thenThrow(new JsonProcessingException("test") {});

  // When
  orderProcessor.emailOnBar(request, httpHeaders, "salesChannel", "lo");

    }

SUT


@InjectMocks
private OrderProcessor orderProcessor;

@Mock
private barServiceConnector barServiceConnector;

@Mock
private BarServiceServiceConfig BarServiceServiceConfig;

@Mock
private ObjectMapper mapper;

@Mock
private ObjectWriter objectWriter;

@Autowired
private barServiceConnector barServiceConnector;

@Autowired
private BarServiceServiceConfig BarServiceServiceConfig;

@Autowired
private static ObjectMapper mapper;

@Autowired
private static ObjectWriter objectWriter;

static {
    if (mapper == null)
        mapper = new ObjectMapper();
    if (objectWriter == null)
        objectWriter = mapper.writer().withDefaultPrettyPrinter();
}

public ImplEmailOnBarOutput emailOnBar(EmailOnBarRequest input, HttpHeaders httpHeaders, String sc, String lo) {
    try {
        LOGGER.debug("Entering emailOnBar method with input: {}, lo: {}, salesChannel: {}", objectWriter.writeValueAsString(input), lo, sc);

        String url = String.format(BarServiceServiceConfig.getEmailOnBarUrl(), lo, sc);
        LOGGER.debug("Calling bar API with URI: {}", url);

        BarResponse BarResponse = barServiceConnector.getOrgbarResponse(url, new HttpEntity<>(input), httpHeaders, HttpMethod.POST);     mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper.readValue(objectWriter.writeValueAsString(BarResponse), ImplEmailOnBarOutput.class);
    } catch (JsonProcessingException e) {
        LOGGER.error("Exception while calling bar-emailOnBar api exception={}", e);
        throw new ErrorJsonProcessingException(e, JSON_PROCESSEING_ERROR_MSG, bar_SERVICE);
    }
}

POJO

@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ImplEmailOnBarOutput {
    @JsonProperty("__EmptyObject__")
    private EmptyObject emptyObject;
}

@Data
@NoArgsConstructor
@JsonSerialize
public class EmptyObject {

}
Share Improve this question edited Mar 25 at 7:14 M. Deinum 126k22 gold badges233 silver badges249 bronze badges asked Mar 25 at 5:19 yodayoda 5673 gold badges12 silver badges34 bronze badges 2
  • 1 Assertion error says that it was expecting it to throw your error, but it didnt which is an error. As for why it didn't, I m not able to comment as the sample code is too messy. i.e. you have two ObjectMapper variables called mapper which shouldnt compile, and you have an @Autowire on a static variable? That doesnt work the way you think it does. Please reanize your code into an minimal reproducible example – pebble unit Commented Mar 25 at 5:58
  • Once again trigger happy dude has downvoted this answer. – yoda Commented Mar 26 at 5:53
Add a comment  | 

1 Answer 1

Reset to default 0

You throwing new JsonProcessingException("test") {}. It is anonymous class.

Try throwing new JsonProcessingException("test").

发布评论

评论列表(0)

  1. 暂无评论