Java Fluent Restful API自动化测试框架

这是一个Restful API自动化测试框架,这是一个能让你写出高可读性测试代码的测试框架!html

项目目标

话说目前行业内,Restful API自动化测试框架已经不是稀罕物了,各个语言都有本身的实现机制。拿Java的Jersey来说,它自己就提供了一个API测试框架-Jersey Test Framework.可以帮助咱们写API测试,可是这里咱们想作的是另外一套。java

观察到Jersey使用了Fluent interface的模式来让代码可读性更高,好比下面:git

String responseMsg = target.path("myresource").request().get(String.class);

那么若是咱们也使用Fluent Interface模式,是否是也可让咱们的测试代码可读性更高呢?
好比下面的测试的代码,是否是看起来很清爽,目标更明确呢?github

APIRequest.GET(URL).header("Authorization", "Bearer " + token).invoke().assertStatus(200).assertBody(expectedBody);

直接一行代码,搞定一条Case!web

分析需求

既然是一个API自动化测试框架,那它能作什么呢?json

  • 可以发HTTP请求 - Get,Post,Put,Delete,甚至 Head
  • 可以接受HTTP返回,而且可以方便验证其返回值
  • 可以打印全部Log,包含Request和Response的全部部分,这样当Case出错时,咱们容易分析问题所在
  • 可以作好数据分离,用配置文件管理测试数据

用到的工具

显然,框架不是工具,它只是对现有工具的组合和再包装,而这个框架也使用了一些流行的工具:app

  • Jersey Client 2.18 咱们要使用它来帮助咱们发HTTP Request
  • Junit4 测试框架,用它来写Case
  • Apache Commons IO 提供Common API帮助读写文件
  • SLF4J,打印log怎能少了它

如何使用

最终,全部的HTTP Request都从APIRequest这个类出发,一步步构建,最终调用Invoke方法发送HTTP 请求。框架

APIResoponse来管理HTTP的返回,这个方法提供一些公共的方法来验证API的返回。工具

建议全部的TestCase都继承与APITest类这样能够方便的管理配置文件,以及得到一些有用的公共方法。测试

下面是一些例子:

  1. 如何发一个Get请求

    APIRequest.GET(uri).header("Authorization", token) .invoke().assertStatus(200).assertBodyContains("expectedContent");

  2. 如何使用XML或者Json格式的Payload

    String payload = loadFile("xmlfile.xml");

  3. 如何运行时定制化Payload填充参数

    String payload = String.format(loadFile("jsonfile.json"), "abc", "edf");

  4. 如何作数据分离,在Property文件管理参数

    `String uri = getValue("get.uri");

核心实现

要想使用Fluent Paragraming Model来写case,那么就得让咱们全部的包装方法,都可以返回指望的Class对象,更重要的是,咱们是想让Request的返回和验证也能参与到Fluent模式的验证,因此在最终调用方法时,APIRequestAPIResponse就要能和谐的过渡到一块儿。
因此咱们这样定义APIRequest类:

/**
 * General Class to make HTTP calls
 * 
 * @author Carl Ji
 */

public class APIRequest {

private UriBuilder uri;
private Map<String, String> params = new HashMap<String, String>();
private Map<String, String> headers = new HashMap<String, String>();
private MediaType contentType = MediaType.APPLICATION_XML_TYPE;
private MediaType acceptType;
private String httpMethod;
private String body;

private APIRequest(String uri, String method)
{
    this.uri=UriBuilder.fromUri(uri);
    this.httpMethod = method;
}

/**
 * Build a HTTP Get request
 * 
 * @param uri
 *        The URI on which a HTTP get request will be called
 * @return
 *        {@link APIRequest} 
 */
public static APIRequest GET(String uri)
{
    return new APIRequest(uri, HttpMethod.GET);
}

/**
 * Build a HTTP Post request
 * 
 * @param uri
 *        The URI on which a POST request will be called
 * @return
 *        {@link APIRequest}
 */
public static APIRequest POST(String uri)
{
    return new APIRequest(uri, HttpMethod.POST);
}

/**
 * Build a HTTP Put request
 * 
 * @param uri
 *        The URI on which a PUT request will be called
 * @return
 *        {@link APIRequest}
 */
public static APIRequest PUT(String uri)
{
    return new APIRequest(uri, HttpMethod.PUT);
}

/**
 * Build a HTTP Delete request
 * 
 * @param uri
 *        The URI that the Delete Request will be called
 * @return
 *        {@link APIRequest}
 */
public static APIRequest DELETE(String uri)
{
    return new APIRequest(uri, HttpMethod.DELETE);
}

/**
 * Build a HTTP HEAD request
 * 
 * @param uri
 *        The URI that the Head request will be called
 * @return
 *        {@link APIRequest}
 */
public static APIRequest HEAD(String uri)
{
    return new APIRequest(uri, HttpMethod.HEAD);
}

/**
 * Add the {@code value} to the end of URI to build the final URI
 * 
 * @param value
 *        The value that will be appended to the URI
 * @return
 *        {@link APIRequest}
 */
public APIRequest path(String value)
{
    this.uri.path(value);
    return this;
}

/**
 * Build the parameter in the request URI
 * 
 * @param key
 *        The request URI parameter key
 * @param value
 *        The request URI parameter value
 * @return
 *        {@link APIRequest}
 */
public APIRequest param(String key, String value)
{
    params.put(key, value);
    return this;
}

/**
 * Set the content type in the request body
 * 
 * @param type
 *        The content type {@link MediaType} 
 * @return
 *        {@link APIRequest}
 */
public APIRequest type(MediaType type)
{
    this.contentType = type;
    return this;
}

/**
 * Set the accepted type for the HTTP response when calling the specific HTTP request
 * 
 * @param type
 *        The accepted type for the response of this request
 * @return
 *        {@link APIRequest}
 */
public APIRequest accept(MediaType type)
{
    this.acceptType = type;
    return this;
}

/**
 * Set the HTTP request headers parameter
 * 
 * @param key
 *        The header name
 * @param value
 *        The corresponding value for the header 
 * @return
 *        {@link APIRequest}
 */
public APIRequest header(String key, String value)
{
    headers.put(key, value);
    return this;
}

/**
 * Set the request body
 * 
 * @param body
 *        The body of the request
 * @return
 *        {@link APIRequest}
 */
public APIRequest body(String body)
{
    this.body = body;
    return this;
}

/**
 * Invoke jersey client to send HTTP request
 * 
 * @return {@link APIResponse}
 */
public APIResponse invoke()
{
    ClientConfig config = new ClientConfig();

    /**
     * Important: Jersey Invocation class will check "Entity must be null for http method DELETE."
     * so we can not send DELETE request with entity in payload, 
     * here we suppress this check
     */
    config.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
    
    Client client = ClientBuilder.newClient(config);
    //Print all logs for each request and response
    client.register(new LoggingFilter(Logger.getLogger(APIResponse.class.getName()), true));
    
    WebTarget webTarget = client.target(uri);
    if(!params.isEmpty())
    {
        for(Entry<String, String> key: params.entrySet())
        {
            webTarget = webTarget.queryParam(key.getKey(), key.getValue());
        }
    }
    
    Invocation.Builder invocationBuilder= webTarget.request();
    if(acceptType != null)
    {
        invocationBuilder = invocationBuilder.accept(acceptType);
    }

    if(!headers.isEmpty())
    {
        for(String key: headers.keySet())
        {
            invocationBuilder.header(key, headers.get(key));
        }
    }
    
    Response response;
    
    if(body == null)
    {
        response= invocationBuilder.method(httpMethod, Response.class);
    }
    else
    {
        response = invocationBuilder.method(httpMethod, Entity.entity(body, contentType), Response.class);
    }
    
    return new APIResponse(response);
}
}

`

源码地址

源码已上传Github:https://github.com/CarlJi/RestfulAPITests
欢迎你们分享讨论,提意见!

未完待续

下一步打算结合个人Junit Extension工具,给框架添加灵活管理Case的能力,这样当Case变多时,就能够按需执行咱们须要的Case。

参考资料

  • Jersey Client使用 https://jersey.java.net/documentation/latest/client.html
  • Jersey Test Framework: http://jersey.java.net/nonav/documentation/latest/test-framework.html
  • Fluent Interface 相关:
    • http://stackoverflow.com/questions/17937755/what-is-the-difference-between-a-fluent-interface-and-the-builder-pattern
    • https://en.wikipedia.org/wiki/Fluent_interface#Problems

若是您看了本篇博客,以为对您有所收获,请点击下面的 [推荐]
若是您想转载本博客,请注明出处大卡的博客[http://www.cnblogs.com/jinsdu/] 若是您对本文有意见或者建议,欢迎留言

相关文章
相关标签/搜索