2016-11-15 120 views
0

我在Spring引导中编写了一个简单的REST,并且以放心编写的测试用例返回http代码400,而它从curl正常工作。Rest-Assured/JUnit返回HTTP错误代码400

服务:

@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 [email protected] 
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 org.apache.http.impl.conn.DefaultClientConnection - 接收响应:HTTP/1.1 400

这里的工作正常卷曲要求:

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卷曲反应和身体:

* 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 
} 

所以我我试图弄清楚我做错了什么。有一件事让我困惑,为什么放心的是在请求中添加'Content-length:0'头部。我正在学习放心和JUnit测试框架,并且我试图让一个GET请求工作。任何帮助,将不胜感激。

回答

0

确定在尝试了几件事情后找到了解决方案。显然,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: <token>"去服务器,而无需换行和工作的其他人怎么叫。

我不完全确定为什么Files.readAllBytes()会添加换行符,因为我在文件中没有换行符。

相关问题