【问题标题】:Convert RestAssured to RestTemplate将 RestAssured 转换为 RestTemplate
【发布时间】:2017-03-10 10:57:11
【问题描述】:

谁能帮我将下面的代码重构为 Spring RestTemplate? postLogin 是稍后在junit e2e 测试中使用的方法。

public class LoginLogoutAPI {

    private static final LoginLogoutAPI INSTANCE = new LoginLogoutAPI();
    private static final String LOGIN_ENDPOINT = "/auth/login";

    public static LoginLogoutAPI getInstance() {
        return INSTANCE;
    }

    public ValidatableResponse postLogin(String login, String password) {
        return given()
                .contentType(JSON)
                .body(getCustomerCredentialsJson(login, password))
                .when()
                .post(LOGIN_ENDPOINT)
                .then()
                .statusCode(SC_OK);
    }

    private Map<String, String> getCustomerCredentialsJson(String login, String password) {
        Map<String, String> customer = new LinkedHashMap<>();
        customer.put("login", login);
        customer.put("password", password);
        return customer;
    }
}

【问题讨论】:

  • 你到底想重构什么?整个街区?
  • 是的,整个区块

标签: java api resttemplate rest-assured


【解决方案1】:

假设您在这里的所有内容都正确,我将实现Rest Template Exchange 方法以进行发布调用并捕获ValidatableResponse 中的响应。

public class LoginLogoutAPI {

    private static final LoginLogoutAPI INSTANCE = new LoginLogoutAPI();
    private static final String LOGIN_ENDPOINT = "/auth/login";

    public static LoginLogoutAPI getInstance() {
        return INSTANCE;
    }

    public ValidatableResponse postLogin(String login, String password) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<byte[]> httpEntity = new HttpEntity<byte[]>(headers);
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(LOGIN_ENDPOINT)
                                                           .queryParam("login",login)
                                                           .queryParam("password",password);
        URI uri=builder.buildAndExpand().toUri();
        ResponseEntity<ValidatableResponse> rs = restTemplate.exchange(uri, HttpMethod.POST, httpEntity,ValidatableResponse.class);
        return rs.getBody();
    }
}

这是一个实现,但不是一个工作示例,因为我没有工作区设置。您必须将 LOGIN_ENDPOINT 替换为其余模板的完整 URL。

如果您需要澄清,请告诉我!

【讨论】:

    猜你喜欢
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2018-05-12
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-10-10
    相关资源
    最近更新 更多