Reputation: 111
I was making a rest-assured test for testing url redirects using testng. I would like to match header location response to match with regular expression.
I am trying to create following method but I didn't find any regular expression matcher using Hamcrest matcher. I would like to use some method like matches (or if any other option) as used in the method.
public Response matchRedirect(String url, Integer statusCode, String urlRegex) {
return
given().
redirects().follow(false).and().redirects().max(0).
expect().
statusCode(statusCode).
header("Location", **matches**(urlRegex)).
when().get(url);
}
Upvotes: 3
Views: 3204
Reputation: 6918
You can create a custom matcher:
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
public class CustomMatchers {
public static Matcher<String> matchesRegex(final String regex) {
return new BaseMatcher<String>() {
public boolean matches(final Object item) {
return ((String) item).matches(regex);
}
public void describeTo(final Description description) {
description.appendText("should match regex: " + regex);
}
};
}
}
And then check that the header match your regex:
public Response matchRedirect(String url, Integer statusCode, String urlRegex) {
return
given().
redirects().follow(false).and().redirects().max(0).
expect().
statusCode(statusCode).
header("Location", CustomMatchers.matchesRegex(urlRegex)).
when().get(url);
}
Upvotes: 1
Reputation: 111
I used class from https://piotrga.wordpress.com/2009/03/27/hamcrest-regex-matcher/ to use with my method.
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
public class RegexMatcher extends BaseMatcher<Object>{
private final String regex;
public RegexMatcher(String regex){
this.regex = regex;
}
public boolean matches(Object o){
return ((String)o).matches(regex);
}
public void describeTo(Description description){
description.appendText("matches regex=");
}
public static RegexMatcher matches(String regex){
return new RegexMatcher(regex);
}
}
Upvotes: 2