代码之家  ›  专栏  ›  技术社区  ›  dave

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

  •  0
  • dave  · 技术社区  · 7 年前

    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(...)) 总是回来 . 因此 result 总是

    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() 返回实际值?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Dar Gar    7 年前
    @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);
    }
    

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