Search code examples
javaspring-bootjunithttp-status-code-401testcase

Java: 401 Unauthorized test case issue in Unit test case for spring boot, REST


everyone.

I have written a test case:

AppManagementApplicationTests.java

@Test
public void testWithAppNameAsNull() {

    Input input = new Input();
    // input type
    String inputTrue = input.appNameAsNullOfAppInfo();
    // response has been stored
    Response response = Response.status(401).entity("").build();

    HttpEntity<String> passingData = new HttpEntity<String>(inputTrue);

    ResponseEntity<String> result = this.restTemplate.postForEntity("/App", passingData, String.class);
    assertEquals(response.getStatus(), result.getStatusCodeValue());

}

Input.java

public String appNameAsNullOfAppInfo() {
    String appName = null;
    String appVersion = "1.1";
    String appKey = "testkey";
    long timestamp = 1487076718;

    AppInfo obj = new AppInfo(appName, appVersion, appKey, timestamp);

    Gson gson = new Gson();

    // searialize into string and return
    return gson.toJson(obj);

}

In my code I am sending

return new ResponseEntity(gson.toJson(response), HttpStatus.UNAUTHORIZED);

So when I run it using Postman it gives the status code as 401

enter image description here

But while testing it is giving an error enter image description here

The URL that I am using is http://localhost:8091/App/ and in the error it is showing http://localhost:41636/App.

And if instead of 401 UNAUTHORISED I change it to 400 BAD_REQUEST, the same test case works absolutely fine. I am not able to figure out why. The line number 139 at which it is showing the error is "ResponseEntity result ="

Thanks in advance.


Solution

  • Quite a simple solution, just need to add a dependency in my 'pom.xml' file:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <scope>test</scope>
    </dependency>
    

    Now my test case is working absolutely fine.