繁体   English   中英

如何模拟接受类类型的通用方法?

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

我正在尝试为REST API客户端编写单元测试。 我遵循的模式在各种其他单元测试中对我来说都很有效。 特别是,我已经成功地模拟了已注入到受测存储库中的依赖项。 但是,当我模拟Spring RestTemplate ,我无法找到一种方法来获取其getForObject()方法以返回null以外的任何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);
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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