I have a FeignClient
I've developed using spring-cloud-starter-openfeign
. I'd like to write a unit test using MockWebServer
. How do I set up the Spring configuration for this?
Asked
Active
Viewed 384 times
0

Doradus
- 938
- 1
- 9
- 15
1 Answers
0
You can do this by configuring client-side load balancing using spring-cloud-starter-loadbalancer
. If you are using Gradle, add this to build.gradle
:
testImplementation 'org.springframework.cloud:spring-cloud-starter-loadbalancer'
Then you can write your test like this:
@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
));
}
}
Then you can write tests like this:
@Test
void demoEndpoint_500_throws() {
demoServer.enqueue(new MockResponse()
.setResponseCode(500));
assertThrows(FeignException.class, () -> client.demoEndpoint());
}

Doradus
- 938
- 1
- 9
- 15