[英]how to match header location response with regular expression using rest-assured
I was making a rest-assured test for testing url redirects using testng. 我正在做一个放心的测试,以使用testng测试URL重定向。 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. 我正在尝试创建以下方法,但是我没有使用Hamcrest匹配器找到任何正则表达式匹配器。 I would like to use some method like matches (or if any other option) as used in the method.
我想使用该方法中使用的某些方法,例如matchs(或其他选项)。
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);
}
I used class from https://piotrga.wordpress.com/2009/03/27/hamcrest-regex-matcher/ to use with my method. 我使用https://piotrga.wordpress.com/2009/03/27/hamcrest-regex-matcher/中的类与我的方法一起使用。
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);
}
}
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.