MockMVC how to test exception and response code in the same test case
You can get a reference to the MvcResult and the possibly resolved exception and check with general JUnit assertions...
MvcResult result = this.mvc.perform( post("/api/some/endpoint") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(someObject))) .andDo(print()) .andExpect(status().is4xxClientError()) .andReturn();Optional<SomeException> someException = Optional.ofNullable((SomeException) result.getResolvedException());someException.ifPresent( (se) -> assertThat(se, is(notNullValue())));someException.ifPresent( (se) -> assertThat(se, is(instanceOf(SomeException.class))));
If you have an exception handler and you want to test for a specific exception, you could also assert that the instance is valid in the resolved exception.
.andExpect(result -> assertTrue(result.getResolvedException() instanceof WhateverException))
You can try something as below -
Create a custom matcher
public class CustomExceptionMatcher extendsTypeSafeMatcher<CustomException> {private String actual;private String expected;private CustomExceptionMatcher (String expected) { this.expected = expected;}public static CustomExceptionMatcher assertSomeThing(String expected) { return new CustomExceptionMatcher (expected);}@Overrideprotected boolean matchesSafely(CustomException exception) { actual = exception.getSomeInformation(); return actual.equals(expected);}@Overridepublic void describeTo(Description desc) { desc.appendText("Actual =").appendValue(actual) .appendText(" Expected =").appendValue( expected);}}
Declare a
@Rule
in JUnit class as below -@Rulepublic ExpectedException exception = ExpectedException.none();
Use the Custom matcher in test case as -
exception.expect(CustomException.class);exception.expect(CustomException .assertSomeThing("Some assertion text"));this.mockMvc.perform(post("/account") .contentType(MediaType.APPLICATION_JSON) .content(requestString)) .andExpect(status().isInternalServerError());
P.S.: I have provided a generic pseudo code which you can customize as per your requirement.