这是针对单元测试,而不是集成测试...
在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 上的测试