您好,
在我的引數化 junit5-test 中,我得到一個 NestedServletException,直到我在我的測驗類上方添加
@ContextConfiguration -Annotation,在該類中我參考了用 @ControllerAdvice 注釋的自定義例外處理程式。在其中,我有用 @ExceptionHandler(ExceptionXY.class) 注釋的方法,用于我想以某種方式處理的所有例外。
拋出 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)
...
拋出例外:org.springframework.web.util.NestedServletException:請求處理失敗;嵌套例外是 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)
...
不拋出例外并像預期的那樣回傳 400。
現在我讀到 @WebMvcTest 應該添加 ControllerAdvices (在本例中為SomeExceptionHandler.class),但在我的情況下似乎不會發生。為什么我必須自己配置背景關系,有沒有辦法在沒有 ContextConfiguration-Annotation 的情況下做到這一點
更新:自定義例外處理程式位于我在 pom.xml 中添加的另一個啟動器中,這會導致該錯誤。
uj5u.com熱心網友回復:
使用@WebMvcTest,只有與 MVC 相關的組件會填充到切片的 Spring 測驗背景關系中。正如您所提到的,您使用 來從不同的啟動器激活自定義例外處理程式@Configuration,默認情況下@WebMvcTest不會填充它,因為它不查找@Configuration類。
您仍然可以@Import(NameOfYourConfig.class)在測驗類的頂部使用手動添加配置,以使用更多 bean 來豐富切片的測驗背景關系。
有關更多資訊,請參閱 Spring Boot 檔案或此Spring Boot 測驗切片概述中的相關部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/380135.html
