简体   繁体   English

使用Regex断言RestAssured响应体

[英]Assert RestAssured response body with Regex

I am trying to assert a timestamp field in json response body using RestAssured as part of my integration tests. 我试图在我的集成测试中使用RestAssured在json响应体中声明一个时间戳字段。 I am not sure which is the right method to perform regex match 我不确定哪种方法可以执行正则表达式匹配

Here is the json response: 这是json的回应:

{
"timestamp": "2018-06-05T23:56:09.653+0000",
"status": 200,
"error": "None",
"message": "None"
}

This is my code for my RestAssured response assertion 这是我的RestAssured响应断言的代码

String pattern = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}.\\d{3}(\\+|\\-)\\d{4}$";
Pattern r = Pattern.compile(pattern);
response.then().assertThat()
    .body("timestamp", matchesPattern(pattern)) //<= ERROR HERE
    .body("status", equalTo(999))
    .body("error", containsString("None"))
    .body("message", containsString("None"));

When I compile the above code I am getting error while verifying timestamp pattern 当我编译上面的代码时,我在验证时间戳模式时遇到错误

  required: java.lang.String,java.lang.CharSequence
  found: java.lang.String
  reason: actual and formal argument lists differ in length

I am not sure which method will support in hamcrest for regex pattern check. 我不确定哪个方法将支持hamcrest进行正则表达式模式检查。

The problem here is there are no right dependencies in my project. 这里的问题是我的项目中没有正确的依赖项。 org.hamcrest.core doesn't have method for matchesPattern . org.hamcrest.core没有matchesPattern方法。 After adding the below dependency the following import worked 添加以下依赖项后,以下导入工作

<!-- https://mvnrepository.com/artifact/org.hamcrest/java-hamcrest -->
<dependency>
  <groupId>org.hamcrest</groupId>
  <artifactId>java-hamcrest</artifactId>
  <version>2.0.0.0</version>
  <scope>test</scope>
</dependency>

You need to import the below code 您需要导入以下代码

import static org.hamcrest.text.MatchesPattern.matchesPattern;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM