我正在使用Spring Webflux开发服务。我使用实现了异常处理@ControllerAdvice
。它工作得很好,但是当我运行集成测试时,似乎@ControllerAdvice
未加载带注释的组件,从而导致以下响应:
{
"timestamp":"2019-11-28T08:56:47.285+0000",
"path":"/fooController/bar",
"status":500,
"error":"Internal Server Error",
"message":"java.lang.IllegalStateException: Could not resolve parameter [1] in protected org.springframework.http.ResponseEntity<it.test.model.Response> it.test.exception.ExceptionHandlerController.handleServiceException(java.lang.Exception,org.springframework.web.context.request.WebRequest): No suitable resolver
}
这是我的控制器建议:
@ControllerAdvice
public class ExceptionHandlerController extends ResponseEntityExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(ExceptionHandlerController.class);
@ExceptionHandler
protected ResponseEntity<Response> handleServiceException(Exception ex, WebRequest request) {
this.logger.error("Error occurred: \"{}\"", ex.getMessage());
Response<Foo> response = new Response<>(new Foo(),
"generic error",
HttpStatus.INTERNAL_SERVER_ERROR);
return new ResponseEntity<>(response, null, HttpStatus.OK);
}
}
这是我的综合测试课
@ExtendWith(SpringExtension.class)
@WebFluxTest(MyController.class)
@ContextConfiguration(classes = {MyController.class, MyServiceImpl.class, ExceptionHandlerController.class })
public class MyControllerIT {
@Autowired
private WebTestClient webTestClient;
@Test
public void testShouldFail() throws IOException {
return this.webTestClient.get()
.uri(uri)
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.statusCode").isEqualTo(500);
}
}
如果你读的文档为@WebFluxTest
它规定:
可以用于仅关注Spring WebFlux组件的Spring WebFlux测试的注释。
使用此批注将禁用完全自动配置,而是仅应用与WebFlux测试相关的配置(即@ Controller,@ ControllerAdvice,@ JsonComponent,Converter / GenericConverter和WebFluxConfigurer Bean,而不是@ Component,@ Service或@Repository bean)。
通常,@ WebFluxTest与@MockBean或@Import结合使用以创建@Controller bean所需的任何协作者。
如果要加载完整的应用程序配置并使用WebTestClient,则应考虑将@SpringBootTest与@AutoConfigureWebTestClient结合使用,而不要使用此注释。
这意味着
@ContextConfiguration(classes = {MyController.class, MyServiceImpl.class, ExceptionHandlerController.class })
是不是什么ü在这里使用。该@WebFluxTest
标注不加载@Component
,@Service
或@Repository
它主要用于仅测试RestControllers及其建议。
您选择的选项似乎是:
@SpringBootTest
而不是结合使用@AutoConfigureWebTestClient
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句