![](/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.