简体   繁体   中英

Unit test a FeignClient using MockWebServer

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?

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());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM