java - 如何使用 junit 5 (Jupiter) 模拟 RestTemplate 交换

标签 java unit-testing spring-boot mockito junit5

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

请帮助我解决以下代码。

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

最佳答案

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

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

关于java - 如何使用 junit 5 (Jupiter) 模拟 RestTemplate 交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53297209/

相关文章:

node.js - 如何在Service构造函数中对Controller和模拟@InjectModel进行单元测试

java - 我正在尝试将 mongodb 与 spring boot 连接。我很困惑何时使用以下 : 中的哪个 Maven 依赖项

java - 当我的应用程序停止时我该如何捕获?

java - 重新安装 Eclipse ADT 保持工作区的状态

java - jdbc :embedded-database throwing HsqlException

ios - 由 UIKeyboardState 更改的 UIViewController 框架的单元测试

java - 来自 SQL View 的嵌套 JSON 响应

java - 将 JFrame 加载到 html 中

java - 如何从条件中获取查询?

c# - 使用 Rhino.Mocks stub 属性 setter 以在调用时执行操作?