简体   繁体   中英

How do I mock a generic method that accepts a class type?

I'm trying to write a unit test for a REST API client. I am following a pattern that has worked well for me in a variety of other unit tests. In particular, I have successfully mocked dependencies that have been injected into a repository under test. However, when I come to mock a Spring RestTemplate , I cannot find a way to get its getForObject() method to return anything other than null . Does anyone know how to do this? I suspect the issue might be that the signature for RestTemplate.getForObject() contains generics:

public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException

Here is my REST client class that I am trying to test:

@Repository
public class WebApplicationClient {
    private final RestTemplate template;
    public WebApplicationClient(RestTemplate template) {
        this.template = template;
    }
    public <T> T getData(String baseUrl, Class<T> clazz) {
        String endpoint = process(baseUrl);
        try {
            return template.getForObject(endpoint, clazz);  // Mock this call during testing
        } catch (HttpClientErrorException | HttpServerErrorException e) {
            String msg = "API call failed: " + endpoint;
            LOG.warn(msg, e);
            throw new WebApplicationException(e.getStatusCode(), msg, e);
        }
    }
}

Here is my unit test so far. What ever I try for when(template.getForObject(...)) always returns null . Hence result is always null and my assertion fails.

public class WebApplicationClientUnitTests {
    @Mock private RestTemplate template;
    private WebApplicationClient client;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        client = new WebApplicationClient(template);
    }

    @Test
    public void getData_Test1() {
        // when(template.getForObject(any(), eq(String.class))).thenReturn("sample"); // Returns null
        when(template.getForObject(any(), any())).thenReturn("sample"); // Returns null

        String result = client.getData(TEST_URL, "db", expectedState, String.class);
        Assert.assertEquals("sample", result);
    }
}

How do I get getForObject() to return an actual value?

@Test
public void getData_Test1() {

    when(template.getForObject((String) any(),eq(String.class))).thenReturn("sample");
    //OR
    //when(template.getForObject((String) any(),(Class)any())).thenReturn("sample");
    //OR
    //when(template.getForObject(any(String.class), any(Class.class))).thenReturn("sample");

    String result = client.getData("TEST_URL", String.class);
    Assert.assertEquals("sample", result);
}

The Above code works fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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