Hello
in my parameterized junit5-test i get a NestedServletException until i add the
@ContextConfiguration-Annotation above my test class in which i reference my custom exception handler that is annotated with @ControllerAdvice. In it i have methods annotated with @ExceptionHandler(ExceptionXY.class) for all exceptions i want to handle in a certain way.
Example that throws NestedServletException
@ExtendWith(SpringExtension.class)
@WebMvcTest(value = SomeController.class)
@WithMockUser("[email protected]")
class SomeControllerIntegrationTest {
@ParameterizedTest
@CsvSource({"1000,-100",
"100,1000000",
"-8,500",})
void getInfoForSomething_invalidInputCheck_Status400(int valA, int valB){
//act
mockMvc.perform(get("v1/anApiEndpoint/" valA "/furtherInformation/" valB "/getBirthday"))
.andExpect(status().isBadRequest)
...
Throws Exception :org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.validation.ConstraintViolationException: SomeDto.valA: must be less than or equal to 10
@ExtendWith(SpringExtension.class)
@WebMvcTest(value = SomeController.class)
@ContextConfiguration(classes = {SomeExceptionHandler.class, SomeController.class, SomeService.class})
@WithMockUser("[email protected]")
class SomeControllerIntegrationTest {
@ParameterizedTest
@CsvSource({"1000,-100",
"100,1000000",
"-8,500",})
void getInfoForSomething_invalidInputCheck_Status400(int valA, int valB){
//act
mockMvc.perform(get("v1/anApiEndpoint/" valA "/furtherInformation/" valB "/getBirthday"))
.andExpect(status().isBadRequest)
...
Throws no Exception and returns 400 like expected.
Now i read that @WebMvcTest should add the ControllerAdvices (in this case SomeExceptionHandler.class) but it seems not to happen in my case. Why do i have to configure the context myself and is there a way to do it without that ContextConfiguration-Annotation
UPDATE: The custom exception handler is in another starter that i have added in my pom.xml maby this leads to that error.
CodePudding user response:
With @WebMvcTest
, only MVC-related components get populated in the sliced Spring Test Context. As you've mentioned that you activate the custom exception handler from a different starter using @Configuration
, that won't be populated by default as @WebMvcTest
doesn't look for @Configuration
classes.
You can still manually add your configuration using @Import(NameOfYourConfig.class)
on top of your test class to enrich the sliced Test Context with further beans.
For more information, consider the relevant section in the Spring Boot documentation or this Spring Boot Test slice overview.