简体   繁体   中英

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. 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); 
}

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);
  }
}

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); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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