Passing Test Data from test

The test we authored in the previous section, the userId was hard coded in the url @GET("/api/users/2")

public class UserClient extends RetrofitBaseClient {

    private interface UserService {

        @GET("/api/users/2")
        Call<GetSingleUserResponse> GetSingleUser();

Pass test data from test layer

The userId is part of the Test Data and must flow from the Test layer.

The userId is a path parameter in the rest request. Let us see how to bring this change.




Final code

UserTests.java

package ekam.example.api;

import com.testvagrant.ekam.testBases.testng.APITest;
import static com.testvagrant.ekam.commons.LayoutInitiator.*;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class UserTests extends APITest {

    @Test(groups = "api")
    public void shouldReturnSingleUser() {

        int userId = 2;

        GetSingleUserResponse user = Client(UserClient.class)
                .getSingleUser(userId);
        assertNotNull(user.getData().getEmail());

    }
}

UserClient.java

package ekam.example.api;

import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.testvagrant.ekam.api.retrofit.RetrofitBaseClient;
import com.testvagrant.ekam.reports.annotations.APIStep;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;

public class UserClient extends RetrofitBaseClient {

    private interface UserService {

        @GET("/api/users/{id}")
        Call<GetSingleUserResponse> getSingleUser(@Path("id") int userId);
    }

    private final UserService service;

    @Inject
    public UserClient(@Named("baseUrl") String baseUrl) {
        super(baseUrl);
        service = httpClient.getService(UserService.class);
    }

    @APIStep(keyword = "When", description = "I invoke getSingleUser API")
    public GetSingleUserResponse getSingleUser(int userId) {
        Call<GetSingleUserResponse> call = service.getSingleUser(userId);
        return httpClient.execute(call);
    }
}

Execute test