我需要对使用WebClient
的类进行单元测试。有没有什么好的方法来处理WebClient?
使用RestTemplate
,我可以轻松使用Mockito。模拟WebClient有点单调乏味,因为深层存根不能与web客户端一起工作......
我想测试我的代码是否提供了正确的标头... 缩短的示例代码:
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() {
...
}
}
答案 0 :(得分:3)
这是针对单位,而非集成测试...
在 Kotlin 中实施,这有点简陋,但它很有效。这个想法可以从下面的代码中提取
首先, WebClient 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上进行测试
答案 1 :(得分:1)
这将在未来的Spring Framework版本MockRestServiceServer
中得到支持;见SPR-15286