当前位置: 首页 > 知识库问答 >
问题:

Rest Assured/JUnit返回HTTP错误代码400

马欣德
2023-03-14

我在Spring boot中编写了一个简单的REST,用rest assured编写的一个测试用例返回http代码400,而它在curl中运行良好。

服务:

@RestController
@RequestMapping("/customerService")
public class CustomerService
{
    private static final Logger logger = Logger.getLogger(CustomerService.class.getName());

    @RequestMapping(value = "/customers/{id}", 
        produces = { "application/hal+json", "application/json" }, 
        consumes = { "application/json" }, method = RequestMethod.GET)
    public ResponseEntity<Customer> getCustomer(@PathVariable (value="id") String id)
    {
        logger.debug("getCustomer ["+id+"]");

        Customer customer = new Customer();
        ResponseEntity<Customer> response = ResponseEntity.ok(customer);

        customer.id="10";
        customer.name="Foobar";
        customer.category="Elite";

        return response;
    }
}

测试类:

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

import static com.jayway.restassured.RestAssured.given;
import static org.junit.Assert.assertNotNull;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

@FixMethodOrder (MethodSorters.NAME_ASCENDING)
public class TestCustomer 
{
    @Test
    public void testStatus() throws IOException
    {
        String token = this.loadContentsFromFile("./src/test/resources/user-token.txt");
        String response = 
                given()
                .header("Authorization",token).and().header("Accept","application/json")
                .contentType("application/json")
                .when()
                    .get("http://localhost:8080/customerService/customers/10")
                   .peek() // Use peek() to print the ouput
                    .asString();

        assertNotNull(response);
        System.out.println("body : " +response);
    }   
    public String loadContentsFromFile(String path) throws IOException 
    {
        return new String(Files.readAllBytes(Paths.get(path)));
    }
}

测试跑步者:

public class TestSuite {
    public static void main(String[] args) {
        Result result = JUnitCore.runClasses(TestCustomerService.class);

        for (Failure failure : result.getFailures()) {
            System.out.println(failure.toString());
        }

        System.out.println(result.wasSuccessful());
    }
}

测试输出:

customer.TestCustomer > testStatus STANDARD_OUT
DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Get connection for route {}->http://localhost:8080
DEBUG org.apache.http.impl.conn.DefaultClientConnectionOperator - Connecting to localhost:8080
DEBUG org.apache.http.client.protocol.RequestAddCookies - CookieSpec selected: ignoreCookies
DEBUG org.apache.http.client.protocol.RequestAuthCache - Auth cache not set in the context
DEBUG org.apache.http.client.protocol.RequestProxyAuthentication - Proxy auth state: UNCHALLENGED
DEBUG org.apache.http.impl.client.DefaultHttpClient - Attempt 1 to execute request
DEBUG org.apache.http.impl.conn.DefaultClientConnection - Sending request: GET /customerService/customers/10 HTTP/1.1
DEBUG org.apache.http.wire -  >> "GET /customerService/customers/10 HTTP/1.1[\r][\n]"
DEBUG org.apache.http.wire -  >> "Content-Type: application/json; charset=UTF-8[\r][\n]"
DEBUG org.apache.http.wire -  >> "Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyIiwiYXVkaWVuY2UiOiJ3ZWIiLCJjcmVhdGVkIjoxNDc5MTM5ODg4NzM0LCJleHAiOjE0Nzk3NDQ2ODh9.YaaNqBXGo3M3fDI0HOL9eRH1G_w0iEZ4ZRxDPE004_QP59ieP20IJv3b1Y74R642yK9I2gjm-YoVvfmM3oqIEQ[\n]"
DEBUG org.apache.http.wire -  >> "[\r][\n]"
DEBUG org.apache.http.wire -  >> "Accept: application/json[\r][\n]"
DEBUG org.apache.http.wire -  >> "Content-Length: 0[\r][\n]"
DEBUG org.apache.http.wire -  >> "Host: localhost:8080[\r][\n]"
DEBUG org.apache.http.wire -  >> "Connection: Keep-Alive[\r][\n]"
DEBUG org.apache.http.wire -  >> "User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_112)[\r][\n]"
DEBUG org.apache.http.wire -  >> "Accept-Encoding: gzip,deflate[\r][\n]"
DEBUG org.apache.http.wire -  >> "[\r][\n]"
DEBUG org.apache.http.headers - >> GET /customerService/customers/10 HTTP/1.1
DEBUG org.apache.http.headers - >> Content-Type: application/json; charset=UTF-8
DEBUG org.apache.http.headers - >> Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ1c2VyIiwiYXVkaWVuY2UiOiJ3ZWIiLCJjcmVhdGVkIjoxNDc5MTM5ODg4NzM0LCJleHAiOjE0Nzk3NDQ2ODh9.YaaNqBXGo3M3fDI0HOL9eRH1G_w0iEZ4ZRxDPE004_QP59ieP20IJv3b1Y74R642yK9I2gjm-YoVvfmM3oqIEQ

DEBUG org.apache.http.headers - >> Accept: application/json
DEBUG org.apache.http.headers - >> Content-Length: 0
DEBUG org.apache.http.headers - >> Host: localhost:8080
DEBUG org.apache.http.headers - >> Connection: Keep-Alive
DEBUG org.apache.http.headers - >> User-Agent: Apache-HttpClient/4.5.2 (Java/1.8.0_112)
DEBUG org.apache.http.headers - >> Accept-Encoding: gzip,deflate
DEBUG org.apache.http.wire -  << "HTTP/1.1 400 [\r][\n]"
DEBUG org.apache.http.wire -  << "Transfer-Encoding: chunked[\r][\n]"
DEBUG org.apache.http.wire -  << "Date: Tue, 15 Nov 2016 02:26:21 GMT[\r][\n]"
DEBUG org.apache.http.wire -  << "Connection: close[\r][\n]"
DEBUG org.apache.http.wire -  << "[\r][\n]"
DEBUG org.apache.http.impl.conn.DefaultClientConnection - Receiving response: HTTP/1.1 400
DEBUG org.apache.http.headers - << HTTP/1.1 400 
DEBUG org.apache.http.headers - << Transfer-Encoding: chunked
DEBUG org.apache.http.headers - << Date: Tue, 15 Nov 2016 02:26:21 GMT
DEBUG org.apache.http.headers - << Connection: close
WARN com.jayway.restassured.internal.RequestSpecificationImpl$RestAssuredHttpBuilder - Could not parse content-type: Response does not have a content-type header
DEBUG com.jayway.restassured.internal.RequestSpecificationImpl$RestAssuredHttpBuilder - Parsing response as: application/octet-stream
DEBUG com.jayway.restassured.internal.RequestSpecificationImpl$RestAssuredHttpBuilder - Parsed data to instance of: class org.apache.http.conn.EofSensorInputStream
DEBUG org.apache.http.wire -  << "0[\r][\n]"
DEBUG org.apache.http.wire -  << "[\r][\n]"
DEBUG org.apache.http.impl.conn.BasicClientConnectionManager - Releasing connection org.apache.http.impl.conn.ManagedClientConnectionImpl@32f271d9
DEBUG org.apache.http.impl.conn.DefaultClientConnection - Connection 0.0.0.0:41492<->127.0.0.1:8080 shut down
HTTP/1.1 400 
Transfer-Encoding: chunked
Date: Tue, 15 Nov 2016 02:26:21 GMT
Connection: close
Executing test testStatus [customer.TestCustomer] with result: SUCCESS

以下行显示返回400:

DEBUG 组织 apache.http.impl.conn.DefaultClientConnection - 正在接收响应: HTTP/1.1 400

下面是一个很好的curl请求:

curl -v --header 'Content-type: application/json' \
--header 'Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZGllbmNlIjoid2ViIiwiY3JlYXRlZCI6MTQ3ODg4ODk0ODExNiwiZXhwIjoxNDc5NDkzNzQ4fQ.nA-5UY3L6HQP-TUjhYgMg1wcQa1Q1GQwPtGxbU3wgctO_c7vMmOd_hhG4Dj28x8dswivVBTCAXYJd1-37CQFfg' \
--request GET http://localhost:8080/customerService/customers/10 \

下面是返回代码为 200 和正文的 curl 响应:

*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /customerService/customers/10 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.47.0
> Accept: */*
> Content-type: application/json; charset=UTF-8
> Authorization: eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1ZGllbmNlIjoid2ViIiwiY3JlYXRlZCI6MTQ3ODg4ODk0ODExNiwiZXhwIjoxNDc5NDkzNzQ4fQ.nA-5UY3L6HQP-TUjhYgMg1wcQa1Q1GQwPtGxbU3wgctO_c7vMmOd_hhG4Dj28x8dswivVBTCAXYJd1-37CQFfg
> 
< HTTP/1.1 200 
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Content-Type: application/hal+json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Tue, 15 Nov 2016 02:47:53 GMT
< 
{
  "id" : "10",
  "name" : "Foobar",
  "category" : "Elite"
* Connection #0 to host localhost left intact
}

所以我试图弄清楚我做错了什么。有一件事让我感到困惑,为什么放心是添加“内容长度:0”标头到请求。我正在学习放心和JUnit测试框架,我被困在试图让一个GET请求工作。任何帮助将不胜感激。

共有2个答案

巩选
2023-03-14

如果您正在使用URIBuilder或类似的东西,请确保移动它添加的所有字符,例如%3等

许学真
2023-03-14

好的,在尝试了一些事情后找到了解决方案。显然,Files.readAllBytes()正在向令牌值添加换行符。所以我替换了loadContentsFromFile方法,使用Scanner读取运行良好的文件

public String loadContentsFromFile(String path) throws IOException 
{
    Scanner scanner=null;
    String text="";
    try
    {
        scanner= new Scanner(new File(path));
        text = scanner.next();
    }
    finally
    {
        scanner.close();
    }
    return text;
    //      return new String (Files.readAllBytes(Paths.get(path)),Charset.defaultCharset());
    //has a bug it adds a line break at the end.
}

因此,这导致标题“Authorization:

我不太清楚为什么是Files。readAllBytes()添加了换行符,因为我在文件中没有换行符。

 类似资料:
  • 在我的MySQL数据库中,我有一个表"table1",在列"name"上设置了唯一约束-我想防止重复的名称。 如果表中已经有名字'John',则此代码: 应该抛出insertUnonnequeException()(我自己的异常)。相反,它抛出InsertException()。 查询的执行返回false,执行进入if()循环。另外$db- 我不知道为什么当发生唯一密钥约束冲突时,mysqli不返

  • 使用一个自定义的Spring Security过滤器,如果HTTP头不包含特定的键值对,我想返回一个HTTP401错误代码。 示例: 据我所知,我可以做到以下几点: 或 (2)抛出一个异常,最终导致Spring Security向客户端抛出一个401错误。 如果#1是更好的选项,我如何在对响应调用之后跳过筛选器链? 或者,如果#2是正确的方法,我应该抛出哪个异常?

  • 我试图开发一个android应用程序使用华为网站套件。我现在正在跟踪这个codelab:https://developer.huawei.com/consumer/en/codelab/hmssitekit/index.html#0我完全按照codelab说的做了一切,但是当我运行我的应用程序时,它抛出了一个错误,在日志中它说“错误代码6” 以前有人收到过同样的错误并解决了吗?请帮帮我

  • 问题内容: Iam尝试对https URL进行身份验证,但Iam出现异常。下面是代码。 例外情况: 请任何人建议如何解决此问题。 问题答案: 401错误代码表示“未经授权”。我相信您的代码无法正确编码Authentication标头。假设服务器需要 基本访问身份验证, 则代码应如下所示: RFC 2617 中提供了HTTP基本和摘要身份验证方案的全面描述

  • 在Spring MVC@RequestMapping注释中,我返回JSP页面名称作为结果。这将返回HTTP状态代码200OK。如何将此状态代码更改为创建的201? @ResponseStatus不起作用。另外,HttpServletResponse也不能工作,因为我只需要返回自定义JSP页面。

  • 问题内容: 我试图从桌面应用程序连接到URL,但出现问题标题中指示的错误,但是当我尝试从servlet连接到同一URL时,一切正常。当我从浏览器加载URL时,一切正常。我在servlet中使用相同的代码。该代码在库中,当它不起作用时,我将代码拉到当前项目中的类中,但它不起作用。 网址https://graph.facebook.com/me。 代码片段。 我在这里有些困惑,是否存在某种不是普通桌面