如何模拟接受类类型的泛型方法



我正在尝试为 REST API 客户端编写单元测试。我遵循的模式在各种其他单元测试中对我很有用。特别是,我已经成功地模拟了已注入到待测试存储库中的依赖项。但是,当我来嘲笑一个 Spring RestTemplate 时,我找不到一种方法来让它getForObject()方法返回除 null 以外的任何内容。有谁知道如何做到这一点?我怀疑问题可能是RestTemplate.getForObject()的签名包含泛型:

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

这是我正在尝试测试的 REST 客户端类:

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

这是我到目前为止的单元测试。无论我尝试什么when(template.getForObject(...))总是返回null.因此,result总是null,我的断言失败了。

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

如何让getForObject()返回实际值?

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

上面的代码对我来说效果很好。

最新更新