Overcoming hardcoded values with enum class




Hi, all welcome to another of my lockdown blog series posts. In this post, I will discuss the use of enum classes to help with managing constants and reducing the use of hardcoded values. When writing RestAssured test one way to pass the api endpoint is as below

    @Test
    public void testLKCode() throws java.io.IOException {
        apiResource= SpecBuilderUtil.valueOf("getLKEndPoint");

        given().
                spec(requestSpec()).
                when().
                get("/lk/10350").
                then()
                .spec(responseSpec());
    }
 
Having code like above is fine as long as that GET resource is used in a maximum of one or two places. However, lets say we have hundreds of test that refer to the API resource path. If the resource path is updated for some reason, then the changes have to be done in multiple places thus making code maintenance a nightmare. This is where we can make use of enum classes.

Take a look at the below code, hear the global variable resource path is returned with the endpoint type when the test calls the getResource method. In this code, the resource paths are specified in two methods of getLKEndPoint and getUSEndPoint. From our test class when we pass the required resource name as shown below the global variable of resourcePath will look for the matching resource name and return the correct API endpoint value such as /lk/10350
 

package SpecBuilder;

public enum  SpecBuilderUtil {

    getLKEndPoint("/lk/10350"),
    getUSEndPoint("/us/90201");

    private String resourcePath;

    SpecBuilderUtil(String resourcePath){

        this.resourcePath=resourcePath;
    }

    public String getResource(){
        return resourcePath;
    }
}

Shown below is how we can pass the required resource name from our test method and then obtain the API endpoint. As shown below from line 53 we pass the required resource name for the test and then from line 58 we can see how the test obtains the matching resource path.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package SpecBuilder;

import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.filter.log.RequestLoggingFilter;
import io.restassured.filter.log.ResponseLoggingFilter;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.specification.ResponseSpecification;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.FileOutputStream;
import java.io.PrintStream;
import static io.restassured.RestAssured.given;

public class SpecBuilderTest extends GlobalVariables{

    public static  PrintStream log;
    SpecBuilderUtil apiResource;
    RequestSpecification requestSpecification;


    @BeforeTest
    public RequestSpecification requestSpec() throws java.io.IOException {

        if (requestSpecification == null) {
            log = new PrintStream(new FileOutputStream("new-log3.txt"), true);
            log.append("*********************TestResults**********************\r");

            requestSpecification = new RequestSpecBuilder()
                    .setBaseUri(GlobalVariables.getGlobalVariables("baseURL"))
                    .setContentType(ContentType.JSON)
                    .addFilter(new RequestLoggingFilter(log))
                    .addFilter(new ResponseLoggingFilter(log))
                    .build();
            return requestSpecification;
        }
        return requestSpecification;
    }

    public ResponseSpecification responseSpec()  {

        ResponseSpecification responseSpecification=new ResponseSpecBuilder()
                .expectStatusCode(200)
                .expectContentType(ContentType.JSON)
                .build();

        return  responseSpecification;
    }
    @Test
    public void testLKCode() throws java.io.IOException {
        apiResource= SpecBuilderUtil.valueOf("getLKEndPoint");
given(). spec(requestSpec()). when(). get(apiResource.getResource()). then() .spec(responseSpec()); } @Test public void testUSCode() throws java.io.IOException { apiResource= SpecBuilderUtil.valueOf("getUSEndPoint"");
given(). spec(requestSpec()). when().log().all(). get(apiResource.getResource()). then() .spec(responseSpec()); } @AfterTest public void cleanup(){ log.append("*********************AfterTestResults**********************"); log.flush(); log.close(); } }

Shown below is the output of the logs generated when the test is invoked

*********************TestResults**********************
Request method:    GET
Request URI:   http://api.zippopotam.us/lk/10350
Proxy:       <none>
Request params:    <none>
Query params:  <none>
Form params:   <none>
Path params:   <none>
Headers:      Accept=*/*
            Content-Type=application/json; charset=UTF-8
Cookies:      <none>
Multiparts:       <none>
Body:        <none>
HTTP/1.1 200 OK
Date: Fri, 10 Apr 2020 02:30:35 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=dfe4b024b6e8733b1517fd320468d8a731586485835; expires=Sun, 10-May-20 02:30:35 GMT; path=/; domain=.zippopotam.us; HttpOnly; SameSite=Lax
X-Cache: hit
Charset: UTF-8
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
CF-Cache-Status: DYNAMIC
Server: cloudflare
CF-RAY: 58190bf5aba7d72d-FRA
Content-Encoding: gzip

{
    "post code": "10350",
    "country": "Sri Lanka",
    "country abbreviation": "LK",
    "places": [
        {
            "place name": "Dehiwala",
            "longitude": "79.8653",
            "state": "",
            "state abbreviation": "CO",
            "latitude": "6.8514"
        }
    ]
}
Request method:    GET
Request URI:   http://api.zippopotam.us/us/90201
Proxy:       <none>
Request params:    <none>
Query params:  <none>
Form params:   <none>
Path params:   <none>
Headers:      Accept=*/*
            Content-Type=application/json; charset=UTF-8
Cookies:      <none>
Multiparts:       <none>
Body:        <none>
HTTP/1.1 200 OK
Date: Fri, 10 Apr 2020 02:30:36 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Set-Cookie: __cfduid=d074be988c60f20bef0e976c317624ca11586485836; expires=Sun, 10-May-20 02:30:36 GMT; path=/; domain=.zippopotam.us; HttpOnly; SameSite=Lax
X-Cache: hit
Charset: UTF-8
Vary: Accept-Encoding
Access-Control-Allow-Origin: *
CF-Cache-Status: DYNAMIC
Server: cloudflare
CF-RAY: 58190bfec8166341-FRA
Content-Encoding: gzip

{
    "post code": "90201",
    "country": "United States",
    "country abbreviation": "US",
    "places": [
        {
            "place name": "Bell",
            "longitude": "-118.1689",
            "state": "California",
            "state abbreviation": "CA",
            "latitude": "33.9767"
        }
    ]
}
*********************AfterTestResults**********************


Comments