首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将RestAssured转换为RestTemplate

将RestAssured转换为RestTemplate
EN

Stack Overflow用户
提问于 2017-03-10 10:57:11
回答 1查看 1.5K关注 0票数 1

请任何人帮助我将下面的代码重构为Spring?postLogin是稍后在junit e2e测试中使用的一种方法。

代码语言:javascript
复制
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;
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-14 16:24:02

假设这里的所有内容都是正确的,我将使用Rest Template Exchange方法实现post调用,并在ValidatableResponse中捕获响应。

代码语言:javascript
复制
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替换为rest模板的完整URL。

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42716689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档