UnsupportedOperationException в интеграционном тесте WebfluxJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 UnsupportedOperationException в интеграционном тесте Webflux

Сообщение Anonymous »

Я пишу интеграционный тест для следующей конечной точки в моей службе Webflux

Код: Выделить всё

@GetMapping
public Mono getUsers() {
Flux users = loadUserService.getusers(getUserIdFromToken());

return users.collectList()
.map(userList -> ResponseEntity.ok(userMapper.map(userList)))
.switchIfEmpty(Mono.just(ResponseEntity.status(HttpStatus.NOT_FOUND).build()));
}
Эта конечная точка работает нормально, когда я запускаю и тестирую службу локально, но в моем интеграционном тесте я получаю исключение UnsupportedOperationException

Код: Выделить всё

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class UserIntegrationTest  {

@Autowired
private WebTestClient webTestClient;

@Autowired
private UserRepository userRepository;

@BeforeAll
void setup() {
userRepository.saveAll(createMockUsers()).subscribe();
}

@AfterAll()
void cleanup() {
userRepository.deleteAll().subscribe();
}

@Test
void test_getUsers() {
initWiremockStubs();

this.webTestClient
.mutateWith(mockJwt().jwt(jwt -> jwt.claim("userid", "12345")))
.get()
.uri("/users")
.exchange()
.expectStatus().isOk();
}
Исключение

Код: Выделить всё

[ERROR] [] o.s.w.s.a.HttpWebHandlerAdapter - [4024b710] Error [java.lang.UnsupportedOperationException] for HTTP GET "/users", but ServerHttpResponse already committed (200 OK)
Error occurred after response was completed: OK(200 OK)[Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json", Content-Length:"2", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Content-Type-Options:"nosniff", X-Frame-Options:"DENY", X-XSS-Protection:"0", Referrer-Policy:"no-referrer"]
org.springframework.web.reactive.function.client.WebClientRequestException: Error occurred after response was completed: OK(200 OK)[Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", Content-Type:"application/json", Content-Length:"2", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Content-Type-Options:"nosniff", X-Frame-Options:"DENY", X-XSS-Protection:"0", Referrer-Policy:"no-referrer"]
at app//org.springframework.web.reactive.function.client.ExchangeFunctions$DefaultExchangeFunction.lambda$wrapException$9(ExchangeFunctions.java:136)
... 258 more
Caused by: java.lang.UnsupportedOperationException
at org.springframework.http.ReadOnlyHttpHeaders.set(ReadOnlyHttpHeaders.java:108)
Во время отладки я обнаружил, что EncoderHttpMessageWriter пытается записать ContentLength в ReadOnlyHttpHeaders, что приводит к исключение UnsupportedOperationException.

Код: Выделить всё

if (inputStream instanceof Mono) {
return body
.singleOrEmpty()
.switchIfEmpty(Mono.defer(() -> {
message.getHeaders().setContentLength(0);
return message.setComplete().then(Mono.empty());
}))
.flatMap(buffer -> {
Hints.touchDataBuffer(buffer, hints, logger);
message.getHeaders().setContentLength(buffer.readableByteCount()); // 

Подробнее здесь: [url]https://stackoverflow.com/questions/76796586/unsupportedoperationexception-in-webflux-integration-test[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»