在我的 Spring Boot 應用程式中,我想撰寫一個 Web 測驗。
我的應用程式回傳一個字串串列。然而,該測驗會生成一個只有一個元素的串列(完整的 json 作為字串)。
我的(最小示例)生產代碼:
@SpringBootApplication
public class BackendApplication {
public static void main(String[] args) {
SpringApplication.run(BackendApplication.class, args);
}
}
@RestController
@RequestMapping("/allBoxes")
class StackOverFlowController {
@GetMapping
public List<String> getNamesOfAllBoxes() {
return List.of("Fruits", "Regional");
}
}
我的測驗課:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class StackOverFlowControllerTest {
@Autowired
WebTestClient webTestClient;
@Test
void whenListOfStringsEndpoint_thenExpectListOfStrings(){
// When
List<String> actual = webTestClient.get()
.uri("/allBoxes")
.exchange()
.expectStatus().is2xxSuccessful()
.expectBodyList(String.class)
.returnResult()
.getResponseBody();
// Then
Assertions.assertEquals(List.of("Fruits", "Regional"), actual);
}
}
我的 maven 依賴項(spring boot 2.7.0 parent):
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
測驗失敗:
org.opentest4j.AssertionFailedError:
Expected :[Fruits, Regional]
Actual :[["Fruits","Regional"]]
但是,如果我通過郵遞員訪問生產應用程式,我會收到:
["Fruits","Regional"]
為什么回應式 WebTestClient 不決議這個 json,而是創建一個只有一個字串的陣列?我如何告訴它決議字串并給我一個字串串列(以我的兩個專案作為元素)?
uj5u.com熱心網友回復:
如果你更換
.expectBodyList(String.class)
經過
.expectBody(new ParameterizedTypeReference<List<String>>() {})
有用。像這樣:
@Test
void whenListOfStringsEndpoint_thenExpectListOfStrings(){
// When
List<String> actual = webTestClient.get()
.uri("/allBoxes")
.exchange()
.expectStatus().is2xxSuccessful()
.expectBody(new ParameterizedTypeReference<List<String>>() {})
.returnResult()
.getResponseBody();
// Then
Assertions.assertEquals(List.of("Fruits", "Regional"), actual);
}
uj5u.com熱心網友回復:
Jackson2Decoder檢查的默認行為Spring WebClient
https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html#webflux-codecs-jackson
對于多值發布WebClient者,默認情況下會先收集值,Flux#collectToList()然后再serializes收集結果集合。
您將需要deserialize相應地。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/485715.html
標籤:爪哇 春天 弹簧靴 spring-webflux
