【问题标题】:Testing a Feign Client测试一个 Feign 客户端
【发布时间】:2021-09-27 21:16:46
【问题描述】:

我编写了一个 feign 客户端,我想使用单元测试来测试它是否有效。

就我而言,集成测试不是当前开发阶段的正确方法。

feign 客户端是null,我在运行测试时收到NullPointerException

如何自动接线?

伪装客户端

package com.myapp.clients;

import com.myapp.model.StatusResponse;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@FeignClient(name="myClient", url="${feign.clients.my.url}")
public interface myClient {

    @RequestMapping(method= RequestMethod.GET, value="/v1/users/{userId}")
    StatusResponse getStatus(
            @RequestHeader(value = "Auth", required = true) String authorizationHeader,
            @RequestHeader(value = "my_tid", required = true) String tid,
            @PathVariable("userId") String userId);

}

测试:

package com.myapp.clients;

import com.intuit.secfraudshared.step.broker.model.StatusResponse;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class MyClientTest {

    @Autowired
    MyClient myClient;
    
    @Test
    public void testmyClient_status200() {

        StatusResponse myResponse = myClient.getStatus("", "tidTestSample", "4626745161770145");
        Assert.assertNotNull(iusResponse);
    }
}

如何自动装配 MyClient?

【问题讨论】:

    标签: spring-cloud-feign openfeign


    【解决方案1】:

    到目前为止,在尝试测试 Feign 客户端时对我有用的方法是通过wiremock 对响应进行存根。你需要为wiremock添加依赖。

    testImplementation 'org.springframework.cloud:spring-cloud-contract-wiremock'
    

    那么你需要注释为

    @RunWith(SpringRunner.class)
    @SpringBootTest(properties = "feign.clients.my.url=http://localhost:${wiremock.server.port}")
    @AutoConfigureWireMock(port = 0)
    

    然后使用wiremock存根。

    stubFor(post(urlPathMatching("/v1/users/([a-zA-Z0-9-]*)")).willReturn(aResponse().withStatus(200).withHeader("content-type", "application/json").withBody("{\"code\":200,\"status\":\"success\"})));
    

    其中([a-zA-Z0-9-]*) 是 {userId} 的正则表达式,假设它是字母数字。

    然后,当然,断言。

    StatusResponse myResponse = myClient.getStatus("", "tidTestSample", "4626745161770145");
    Assert.assertNotNull(myResponse);
    

    【讨论】:

      猜你喜欢
      • 2018-06-01
      • 2018-04-19
      • 2018-10-02
      • 2016-03-27
      • 2018-08-22
      • 2019-11-04
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      相关资源
      最近更新 更多