2017-01-09 89 views
0

我使用restAssured在我們的應用程序中測試rest服務。該應用程序接收Json格式。在調用rest服務之前,RestAssured必須使用toString方法反序列化bean類的字段(ENUM)以實現響應。 按照代碼:在RestAssured中配置反序列化Json

public enum Condition { 

    SUCCESS("success"), 
    FAILURE("failure"); 

    private String condition; 

    private Condition(String condition) { 
     this.condition = condition; 
    } 

    @Override 
    public String toString() { 
     return this.condition; 
    } 
} 


public class Order {  
    private String order_id; 
    private Condition status; 

    //Getters and Setters 
} 


import static com.jayway.restassured.RestAssured.given; 
import static com.jayway.restassured.RestAssured.preemptive; 
import static org.assertj.core.api.Assertions.assertThat; 
import static com.jayway.restassured.config.RestAssuredConfig.config; 
import static com.jayway.restassured.config.ObjectMapperConfig.objectMapperConfig; 

public class RestTests {  

    //.....// 

    private static RequestSpecification spec; 
    public static final Order inputOrderInvalid = 
      new Order.Builder() 
      .setOrderId("213424") 
      .setCondition(Condition.SUCCESS)   
      .build(); 


    @BeforeClass 
    public static void initSpec(){ 

     ObjectMapper objectMapper = new ObjectMapper(); 
     objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);   
     objectMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, false); 

     RestAssuredConfig config = config().objectMapperConfig(objectMapperConfig().jackson2ObjectMapperFactory((cls, charset) -> objectMapper)); 


     spec = new RequestSpecBuilder() 
       .setConfig(config) 
       .setContentType(ContentType.JSON)        
       .setBaseUri(ENDPOINT_URI) 
       .addFilter(new ResponseLoggingFilter())//log request and response for better debugging. You can also only log if a requests fails. 
       .addFilter(new RequestLoggingFilter()) 
       .build(); 
    } 


     @Test 
    public void orderInvalid(){ 
     JsonPath error = given() 
      .spec(spec) 
      .body(inputOrderInvalid)    
      .when() 
      .post(SERVICE) 
      .then() 
      .statusCode(HttpStatus.SC_BAD_REQUEST) 
      .extract() 
      .jsonPath(); 

     assertThat(error.getString("code")).isEqualTo("INCORRECT_VALUE"); 
    } 
    //.....// 
} 

的restAssured只發送requestBody:

{ 
    "order_id" : "12312546", 
    "condition" : "SUCCESS" 
} 

似乎在ObjectMapper設置好的配置已被忽略。 (DeserializationFeature.READ_ENUMS_USING_TO_STRING)。

任何人都可以幫助我嗎?

回答

1

由於我的目標是序列化使用的toString我必須更改序列化功能:

objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true); 

到:

objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true); 

它解決了這個問題。