spring 如何将FeignClient自动连接到测试类中

yeotifhr  于 2023-06-21  发布在  Spring
关注(0)|答案(1)|浏览(102)

我写了一个FeignClient,我想用单元测试来测试它是否工作。(对于我的情况,集成测试不是当前开发阶段的正确方法)。
在我的测试中,FeignClient没有初始化(null):我在运行测试时收到一个NullPointerException

如何成功自动连接FeignClient

  • 虚假客户 *:
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?

g9icjywg

g9icjywg1#

到目前为止,在尝试测试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}的正则表达式,假设它是字母数字。
然后,当然,Assert。

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

相关问题