【问题标题】:How do I mock RestTemplate exchange using junit 5 (Jupiter)如何使用 junit 5 (Jupiter) 模拟 RestTemplate 交换
【发布时间】:2018-11-14 09:48:17
【问题描述】:

我尝试使用以下代码,但在响应正文中我得到了空记录。

请在下面的代码上帮助我。

Java 代码:

    public Customer getCustomers(String customerId, String authorization) {

        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.set("Authorization", authorization);
        HttpEntity<Customer> request = new HttpEntity<>(headers);
        Map<String, Object> params = new HashMap<>();
        params.put("CustomerId", customerId);

        String url = "https://localhost:8080/api/customer/{CustomerId}/get";
        ResponseEntity<Customer> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                request,
                Customer.class,
                params
        );
        Customer customer = null;
        if (response != null && response.getBody() != null) {
            customer = response.getBody();
        }
        return customer;
    }

测试代码:

    @Test
    public void testGetCustomersSuccess() {
        Customer customer = new Customer();
        customer.setCountryCode("countryCode");
        customer.setCreatedFrom("createdFrom");
        customer.setCustomerlandline("224153");
        customer.setCustomermobile("1522252");
        customer.setEmail("email");
        customer.setFirstname("firstName");
        customer.setFiscalCode("fiscalCode");
        customer.setFirstname("lastName");
        customer.setId("5");
        MultiValueMap<String, String> headers=new LinkedMultiValueMap<>();
        headers.set(Authorization,"12152");
        ResponseEntity<Customer> response=new ResponseEntity<Customer>(HttpStatus.OK);
        when(restTemplate.exchange(Mockito.any(String.class),
                Mockito.<HttpMethod> any(),
                Mockito.<HttpEntity<Customer>> any(),
                Mockito.<Class<Customer>> any(),
                Mockito.<String, Object> anyMap()))
        .thenReturn(response);
        assertEquals(response.getBody(),serviceClientImpl.getCustomers("5", "12152"));
        
    }

【问题讨论】:

    标签: java unit-testing spring-boot mockito junit5


    【解决方案1】:

    您需要在响应中设置客户的价值。 您在客户对象中设置的值未在任何地方使用。 试试这个:

    ResponseEntity<Customer> response=new ResponseEntity<Customer>(customer,HttpStatus.OK);
    

    【讨论】:

    • 我发布了问题,然后我意识到我错过了在响应正文中添加客户对象...谢谢。
    猜你喜欢
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 2019-06-08
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    相关资源
    最近更新 更多