繁体   English   中英

使用 MockWebServer 对 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.

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