Michal
Michal

Reputation: 573

Convert RestAssured to RestTemplate

Could anyone please help me with refactoring the code below to Spring RestTemplate? postLogin is a method that is used in junit e2e tests later on.

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

Upvotes: 1

Views: 1712

Answers (1)

Coder
Coder

Reputation: 2239

Assuming that you had everything here correct I am going to make a implementation of Rest Template Exchange method to make the post call and capture the response in 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();
    }
}

It is an implementation but not a working sample as I don't have the workspace setup. You do have to replace your LOGIN_ENDPOINT with the complete URL for the rest template.

Let me know if you need clarification!

Upvotes: 2

Related Questions