Vikram
Vikram

Reputation: 7515

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. I am not sure which is the right method to perform regex match

Here is the json response:

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

This is my code for my RestAssured response assertion

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.

Upvotes: 2

Views: 4772

Answers (1)

Vikram
Vikram

Reputation: 7515

The problem here is there are no right dependencies in my project. org.hamcrest.core doesn't have method for 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;

Upvotes: 3

Related Questions