2016-11-15 118 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()會添加換行符,因爲我在文件中沒有換行符。

相關問題