很多接口都会有 timestamp 字段和 sign 字段(有的是 auth 字段),放在 http 请求的 header 里。
为了代码好看(好吧,就是为了好看而已),不想在每个用例里都写上类似如下的代码:
setTimestamp();
setSign();
given().when().then()
 
其中一种方法就是使用 Filter,或者说 AuthFilter。
Filter 可以在 request 实际发送前,对 request 进行修改。也可以在 response 得到进一步的处理前,修改内容。
Filter 可以指定顺序,也可以形成责任链。
使用 AuthFilter 的好处在于,如果不需要的时候,可以通过如下的代码将 AuthFilter 从责任链中去掉。
given().auth().none()
 
我们自己定义的 Filter 继承自 AuthFilter
package com.szsharelink.test.filter;
import com.jayway.restassured.filter.FilterContext;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.specification.FilterableRequestSpecification;
import com.jayway.restassured.specification.FilterableResponseSpecification;
import com.jayway.restassured.spi.AuthFilter;
import com.szsharelink.test.utils.DateTimeUtils;
import com.szsharelink.test.utils.HttpUtil;
import com.szsharelink.test.utils.SecurityUtils;
import java.util.Map;
/**
 * Created by Liliangxi on 2017/8/15.
 */
public class SetTimeStampAndSignFilter implements AuthFilter{
    private String appkey;
    private String appsecret;
    public SetTimeStampAndSignFilter(String appkey, String appsecret){
        this.appkey = appkey;
        this.appsecret = appsecret;
    }
    public Response filter(FilterableRequestSpecification filterableRequestSpecification, FilterableResponseSpecification filterableResponseSpecification, FilterContext filterContext) {
        String timeStamp = DateTimeUtils.getUTCTimestamp("yyyyMMdd.HHmmss");
        filterableRequestSpecification.header("timestamp", timeStamp);
        switch (filterableRequestSpecification.getMethod()){
            case POST:
                String body = filterableRequestSpecification.getBody().toString();
                filterableRequestSpecification.header("sign", SecurityUtils.calcSign(timeStamp, appkey, appsecret, body));
                break;
            case GET:
                Map<String, String> parameterMap = filterableRequestSpecification.getQueryParams();
                String sortedQueryString = HttpUtil.buildSortedQuery(parameterMap);
                filterableRequestSpecification.header("sign", SecurityUtils.calcSign(timeStamp, appkey, appsecret, sortedQueryString));
                break;
        }
        return filterContext.next(filterableRequestSpecification, filterableResponseSpecification);
    }
}
 
这样,在编写测试用例时,就可以这样来写,来满足一个强迫症患者:
given()
    .contentType("application/json;charset=UTF-8")
    .headers(walletHeaders)
    .filter(new SetTimeStampAndSignFilter(appkey, appsecret))
.when()
    .get(UrlMapper.FundsUrl)
.then()
    .log().ifError()
    .body("code", equalTo("0000"))
    .body(matchesJsonSchemaInClasspath("Funds.json"))
    .body("content.fundList.size()",is(13))