简体   繁体   English

使用 Rest Assured 和 TestNG 处理异常/故障

[英]Handling exceptions/failures using Rest Assured and TestNG

I'm trying to find a universal way of handling errors in my tests which use TestNG as the framework and Rest Assured as the library to make REST calls.我试图在我的测试中找到一种处理错误的通用方法,它使用 TestNG 作为框架,并使用 Rest Assured 作为库来进行 REST 调用。

And in some of Rest Assured @Test annotated methods I enclose within try/catch:在一些 Rest Assured @Test 注释方法中,我将其包含在 try/catch 中:

    @Test
    public void readyForSend(String uid) {

        try{

        Response response =

        given().header("X-AI-Test-ID","new-shop-user").
               spec(requestSpecUserCreationService).
        when().
               get("/api/v11/new/createUser?uid=" + uid ).
        then().
              assertThat().statusCode(200);
        catch(AssertionError ae){
            logger.info("Unable to create new user");
        }
    }

In my TestNG file, I have the following set:在我的 TestNG 文件中,我有以下设置:

<suite name="create new user" verbose="1" configfailurepolicy="continue">

I have over 30 REST calls to make for each iteration and am using eg invocationCount = 10 so one single Rest Assured failure that does not have it's own try/catch and the whole lot fail.我有超过 30 个 REST 调用来进行每次迭代,并且正在使用例如invocationCount = 10所以一个单一的 Rest 保证失败没有它自己的尝试/捕获并且整个失败。 Must I enclose each in a try/catch or is there a better way of doing a 'soft assertion' so the tests do not bomb on me if not handled individually?我必须将每个都包含在 try/catch 中,还是有更好的方法来进行“软断言”,这样如果不单独处理,测试就不会轰炸我?

A simple way would be to simply make a method, which encapsulates the get and other post calls.一种简单的方法是简单地创建一个方法,该方法封装了 get 和其他 post 调用。 You can do further exception handling in this method as well.您也可以在此方法中进行进一步的异常处理。 The status code can be returned and a soft assert can be done post that.可以返回状态代码,并且可以在此之后进行软断言。 eg.例如。

 public static Response doGet(String endpoint) {
            Response response = given(defaultRequestSpec).when().get(endpoint).andReturn();
//defaultRequestSpec can hold your headers, if they are common or pass as arguments
            return response;
        }

In your @Test method, make a call to this method在您的 @Test 方法中,调用此方法

 @Test(invocationCount=10) {
        SoftAssert softAssert = new SoftAssert();
        softAssert.assertEquals(this.doGet("/api/v11/new/createUser?uid=...").statusCode(), 200, "Verify createUser response is 200");
    ....
    //further api calls
    softAssert.assertAll();
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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