我很难搞清楚这一点。
我几乎可以嘲笑所有内容但由于某种原因HttpServletRequest
被嘲笑但未注入@ControllerAdvice
@ExceptionHandler
方法。
有什么想法吗?感谢您的帮助!
STR 使用最少的即插即用测试套件/代码进行回购
https://github.com/krodyrobi/spring-integration-test-str
@Component
public class Config {
private final String url = "https://httpstat.us/";
public String getUrl() {
return url;
}
}
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(WebClientResponseException.class)
public ResponseEntity<String> handleException(HttpServletRequest request, WebClientResponseException ex) {
return new ResponseEntity<>(request.getRequestURL() + " " + ex.getResponseBodyAsString(), ex.getStatusCode());
}
}
@RestController
public class SomeController {
private final Config config;
@Autowired
public SomeController(Config config) {
this.config = config;
}
@GetMapping("/test")
public Mono<String> test() {
return WebClient
.create(config.getUrl())
.get()
.uri("/200")
.retrieve()
.bodyToMono(String.class);
}
}
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {
SomeController.class,
GlobalExceptionHandler.class,
})
public class SomeControllerTest {
private final static String baseUrl = "http://localhost:9999/";
public @Rule WireMockRule wireMockRule = new WireMockRule(9999);
private @MockBean Config config;
private @MockBean HttpServletRequest request;
private WebTestClient webClient;
private @Autowired SomeController controller;
private @Autowired GlobalExceptionHandler exceptionHandler;
@Before
public void setUp() {
webClient = WebTestClient
.bindToController(controller)
.controllerAdvice(exceptionHandler)
.build();
when(config.getUrl()).thenReturn(baseUrl);
}
@Test
public void test_works() {
wireMockRule
.stubFor(get(urlEqualTo("/200"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "text/plain")
.withBody("200 MOCK")));
webClient
.get()
.uri("/test")
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo("200 MOCK");
wireMockRule.verify(getRequestedFor(urlMatching("/200")));
}
@Test
public void test_fails() {
// java.lang.IllegalStateException: No suitable resolver for argument 0
// of type 'javax.servlet.http.HttpServletRequest' on public
// org.springframework.http.ResponseEntity<java.lang.String>
// com.example.demo.GlobalExceptionHandler.handleException(
// javax.servlet.http.HttpServletRequest,
// ...client.WebClientResponseException
// )
wireMockRule
.stubFor(get(urlEqualTo("/200"))
.willReturn(aResponse()
.withStatus(404)
.withHeader("Content-Type", "text/plain")
.withBody("404 MOCK")));
webClient
.get()
.uri("/test")
.exchange()
.expectStatus()
.isNotFound()
.expectBody(String.class)
.isEqualTo("Http://localhost:8080/test 404 MOCK");
wireMockRule.verify(getRequestedFor(urlMatching("/200")));
}
}
答案 0 :(得分:1)
使用以下代替HttpServletRequest
import org.springframework.http.server.reactive.ServerHttpRequest;
ServerHttpRequest request