gpt4 book ai didi

spring-webflux - 如何验证/测试 WebClient 使用情况

转载 作者:行者123 更新时间:2023-12-04 19:30:00 26 4
gpt4 key购买 nike

我需要对使用 WebClient 的类进行单元测试.有没有什么好的方法来处理 WebClient?
RestTemplate我可以轻松使用 Mockito。模拟 WebClient 有点乏味,因为深 stub 不适用于 WebClient...

我想测试我的代码是否提供了正确的标题...
缩短的示例代码:

public class MyOperations {
private final WebClient webClient;

public MyOperations(WebClient webClient) {
this.webClient = webClient;
}

public Mono<ResponseEntity<String>> get( URI uri) {
return webClient.get()
.uri(uri)
.headers(computeHeaders())
.accept(MediaType.APPLICATION_JSON)
.retrieve().toEntity(String.class);
}

private HttpHeaders computeHeaders() {
...
}

}

最佳答案

这是为了单位 , 不是集成测试...

实现于 Kotlin ,这有点初级,但它是有效的。这个想法可以从下面的这段代码中提取出来

首先,一个网络客户端 kotlin 扩展

import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mockito.*
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.WebClientResponseException
import reactor.core.publisher.toMono

fun WebClient.mockAndReturn(data: Any) {
val uriSpec = mock(WebClient.RequestBodyUriSpec::class.java)
doReturn(uriSpec).`when`(this).get()
doReturn(uriSpec).`when`(this).post()
...

val headerSpec = mock(WebClient.RequestBodyUriSpec::class.java)
doReturn(headerSpec).`when`(uriSpec).uri(anyString())
doReturn(headerSpec).`when`(uriSpec).uri(anyString(), anyString())
doReturn(headerSpec).`when`(uriSpec).uri(anyString(), any())
doReturn(headerSpec).`when`(headerSpec).accept(any())
doReturn(headerSpec).`when`(headerSpec).header(any(), any())
doReturn(headerSpec).`when`(headerSpec).contentType(any())
doReturn(headerSpec).`when`(headerSpec).body(any())

val clientResponse = mock(WebClient.ResponseSpec::class.java)
doReturn(clientResponse).`when`(headerSpec).retrieve()
doReturn(data.toMono()).`when`(clientResponse).bodyToMono(data.javaClass)
}

fun WebClient.mockAndThrow() {
doThrow(WebClientResponseException::class.java).`when`(this).get()
doThrow(WebClientResponseException::class.java).`when`(this).post()
...
}

然后, 单元测试
class MyRepositoryTest {

lateinit var client: WebClient

lateinit var repository: MyRepository

@BeforeEach
fun setUp() {
client = mock(WebClient::class.java)
repository = MyRepository(client)
}

@Test
fun getError() {
assertThrows(WebClientResponseException::class.java, {
client.mockAndThrow()
repository.get("x")
})
}

@Test
fun get() {
val myType = MyType()
client.mockAndReturn(myType)
assertEquals(myType, repository.get("x").block())
}
}

备注 :在 JUnit 5 上进行测试

关于spring-webflux - 如何验证/测试 WebClient 使用情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44608983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com