Java:spring 引导单元测试用例中出现 401 未经授权的测试用例问题,REST

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

大家。

我写了一个测试用例:

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

}

在我发送的代码中

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

所以当我 运行 它使用 Postman 时,它给出的状态代码为 401

但是在测试时出现错误

我用的URL是http://localhost:8091/App/ and in the error it is showing http://localhost:41636/App.

如果我将它改为 400 BAD_REQUEST 而不是 401 UNAUTHORIZED,同样的测试用例绝对可以正常工作。 我不知道为什么。显示错误的行号 139 是 "ResponseEntity result ="

提前致谢。

url : http://localhost:8091/App/ 是您的应用 url 由您的服务器 (Tomcat) 定义。

url : http://localhost:41636/App 是由嵌入式服务器为您的测试用例生成的。它由配置 webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT

创建

查看您的测试,它看起来不像是身份验证问题,但似乎传递给您服务的输入参数不正确..

非常简单的解决方案,只需要在我的 'pom.xml' 文件中添加一个依赖项:

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

现在我的测试用例工作得非常好。