簡體   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