![](/img/trans.png)
[英]Mockito.when() not working in a unit test when mocking FeignCLient
[英]Unit test a FeignClient using MockWebServer
我有一個使用spring-cloud-starter-openfeign
FeignClient
我想使用MockWebServer
編寫單元測試。 如何為此設置 Spring 配置?
您可以通過使用spring-cloud-starter-loadbalancer
配置客戶端負載平衡來做到這一點。 如果您使用的是 Gradle,請將其添加到build.gradle
:
testImplementation 'org.springframework.cloud:spring-cloud-starter-loadbalancer'
然后你可以這樣寫你的測試:
@SpringBootTest
class DemoClientTest {
@Autowired
DemoClient client;
static MockWebServer demoServer;
@AfterAll
static void stopMockServer() throws IOException {
demoServer.close();
}
@Configuration
@EnableAutoConfiguration
@EnableFeignClients(clients = DemoClient.class)
static class Config {
static {
demoServer = new MockWebServer();
try {
demoServer.start();
} catch (IOException e) {
throw new AssertionError(e);
}
}
@Bean
ServiceInstanceListSupplier serviceInstanceListSupplier() {
return ServiceInstanceListSuppliers.from("mt-server", new DefaultServiceInstance(
"instance1", "service1",
demoServer.getHostName(), demoServer.getPort(),
false
));
}
}
然后你可以像這樣編寫測試:
@Test
void demoEndpoint_500_throws() {
demoServer.enqueue(new MockResponse()
.setResponseCode(500));
assertThrows(FeignException.class, () -> client.demoEndpoint());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.