簡體   English   中英

如何使用Rest-Assure確保標頭位置響應與正則表達式匹配

[英]how to match header location response with regular expression using rest-assured

我正在做一個放心的測試,以使用testng測試URL重定向。 我想匹配標頭位置響應以與正則表達式匹配。

我正在嘗試創建以下方法,但是我沒有使用Hamcrest匹配器找到任何正則表達式匹配器。 我想使用該方法中使用的某些方法,例如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); 
}

我使用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);
  }
}

您可以創建一個自定義匹配器:

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

}

然后檢查標題是否與您的正則表達式匹配:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM