KerenSi
KerenSi

Reputation: 389

How to Autowire FeignClient into Test Class

I've written a FeignClient and I would like to test that it works using a unit test. (For my case, integration tests is not the right approach for the current development stage).

In my test, the FeignClient is not initialized (null): I receive a NullPointerException while running the test.

How can I successfully Autowire a FeignClient?

Feign client:

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

}

Tests:

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

How can Autowire MyClient?

Upvotes: 6

Views: 12950

Answers (1)

amay
amay

Reputation: 640

The method that has worked for me so far while trying to test Feign Clients is stubbing the response via wiremock. You would need to add dependency for wiremock.

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

Then you would need to annotate as

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

And then stub using wiremock.

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

where ([a-zA-Z0-9-]*) is regex for {userId} assuming it is alphanumeric.

And then, of course, assert.

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

Upvotes: 3

Related Questions