There are many ways to verify an interface: verify all, verify Body (or Data), verify a field, verify the database… Let’s do a quick share today.

We’ve mentioned the interface code at least 800 times, but we haven’t said anything about validation (assertions).

Meaning of assertion

Assertions are often used in Junit to determine whether a test results match expectations, and assertions are added to find errors.

N ways of asserting

The simplest getCode

Assert.assertEquals(expectCode,response.getCode());

Assert.assertEquals(expectMsg,response.getMsg());

Assert.assertEquals(expectStatus,response.getStatus());

Copy the code

The relatively simple getBody

assertEquals(Objects.toString(response.getBody(), ""), expectResult);

Copy the code

Verify all returns 1

Assert.assertEquals(Objects.toString(response, ""), expectData);

Copy the code

Check all returns 2

AssertUtil.isJsonEquals(response, expectData, false);

Copy the code

Validates certain fields – low level version

Validates some fields in the body of the returned data

String body=JSON.toJSONString(response.getBody());

JSONObject jsonObject = JSON.parseObject(body);

JSONArray array = jsonObject.getJSONArray("otherArchiveNumberList");

String s =jsonObject.getString("archiveNumber");

JSONArray array2 =jsonObject.getJSONArray("archiveMergeDetailList");



assertEquals(bodyotherArchiveNumberList,JSON.toJSONString(array));

assertEquals(bodyarchiveNumber,s);

assertEquals(bodyarchiveMergeDetailList,JSON.toJSONString(array2));

Copy the code

Validates certain fields – relative advanced version 1

If the returned data has a value, some fields of data are returned. If data is empty, other fields are returned with an error message.

String Result=JSON.toJSONString(response);

JSONObject jsonObject = JSON.parseObject(Result);

// Verify zrrdahs and ZJLS when data is not null

if (response.getType().equals("SUCCESS"))

    if (jsonObject.getJSONObject("data")! =null) {

    String s = jsonObject.getJSONObject("data").getString("jls");

    AssertJUnit.assertEquals(expectData, s);

            }

// Data is nulltype"Error" indicates that the error message is verified

   if (jsonObject.getJSONObject("data")==null)

   assertEquals(Objects.toString(response.getErrorMessage(), ""), expectErrorMessage);

Copy the code

Other notes:

Assert.assertEquals(Objects.toString(response, “”), expectData);

Objects.tostring (response, “”) is used to avoid null Pointers when data is null.

assertEquals(Objects.toString(response.getErrorMessage(), “”), expectErrorMessage);

Response.geterrormessage () is response with get () and set ().

Since we are talking about here, I will paste the Response, which can be generally used.

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;

import com.alibaba.fastjson.serializer.SerializerFeature;

import org.apache.commons.lang3.StringUtils;

import static org.testng.AssertJUnit.assertEquals;

import static org.testng.AssertJUnit.assertTrue;

/ * *

 *

* Return from the client

* /

public class ApiKhdResponse {



    private String type;



    private Object data;



    private String errorCode;



    private String errorMessage;



    private String reason;



    public JSONObject convert2JsonObject() {

        String dataText = JSON.toJSONString(data, SerializerFeature.WriteMapNullValue);

        JSONObject dataObject = JSON.parseObject(dataText);

        return dataObject;

    }



    public JSONArray convert2JsonArray() {

        String dataText = JSON.toJSONString(data, SerializerFeature.WriteMapNullValue);

        JSONArray dataArray = JSON.parseArray(dataText);

        return dataArray;

    }





    public String getType() {



        return this.type;

    }



    public void setType(String type) {



        this.type = type;

    }





    public Object getData() {

        return data;

    }



    public void setData(Object data) {

        this.data = data;

    }



    public String getErrorCode() {

        return errorCode;

    }



    public void setErrorCode(String errorCode) {

        this.errorCode = errorCode;

    }



    public String getErrorMessage() {

        return errorMessage;

    }



    public void setErrorMessage(String errorMessage) {

        this.errorMessage = errorMessage;

    }



    public String getReason() {

        return reason;

    }



    public void setReason(String reason) {

        this.reason = reason;

    }



    @Override

    public String toString() {

        return "ApiResponse{" +

                "type='" + type + '\''+

                ", data=" + data +

                ", errorCode='
" + errorCode + '\'' +

                "
, errorMessage='" + errorMessage + '\' ' +

                ", reason='" + reason + '\''+

                '
}';

    }

    public <T> T getBodyBean(Class<T> clazz) { return JSON.parseObject(data.toString(), clazz); }

}

Copy the code

Validates certain fields – relative advanced version 2

// Check the return of the data. If code returns normal, check the body, if code returns an exception, give a prompt.

String code=response.getHead().get("code");

  if ("00000000".equals(code)) {

  assertEquals(Objects.toString(response.getBody(), ""), expectResult);

  }else{

  assertEquals(Objects.toString(response.getMsg(), ""), expectResult);

Copy the code

Remark:

If using this validation method requires some special handling in Response, such as writing an assertSuccess() method, I can also post the full content here (though this can be imported automatically when writing assertions).

import com.alibaba.fastjson.JSON;

import com.alibaba.fastjson.JSONArray;

import com.alibaba.fastjson.JSONObject;

import com.alibaba.fastjson.serializer.SerializerFeature;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

import static org.testng.AssertJUnit.assertEquals;

import static org.testng.AssertJUnit.assertTrue;



public class XqyResponse {



    private Map<String, String> head;



    private Object body;



    public JSONObject convert2JsonObject() {

        String bodyText = JSON.toJSONString(body, SerializerFeature.WriteMapNullValue);

        JSONObject bodyObject = JSON.parseObject(bodyText);

        return bodyObject;

    }



    public JSONArray convert2JsonArray() {

        String bodyText = JSON.toJSONString(body, SerializerFeature.WriteMapNullValue);

        JSONArray bodyArray = JSON.parseArray(bodyText);

        return bodyArray;

    }



    public void assertSuccess() {

        String code = head.get("code");

        assertEquals("00000000", code);

    }



    public void assertFailed() {

    String code = head.get("code");

// Some return failed interfaces, code is null

            assertTrue(true);

            return;

        }

assertTrue(! code.equals("00000000") && !code.contains("1111111"));

    }



    public Map<String, String> getHead() {

        return head;

    }



    public void setHead(Map<String, String> head) {

        this.head = head;

    }



    public String getCode() {

        return head.get("code");

    }



    public String getMsg() {

        return head.get("msg");

    }



    public String getStatus() {

        return head.get("status");

    }



    public String getTime() {

        return head.get("time");

    }



    public Object getBody() {

        return body;

    }



    public void setBody(Object body) {

        this.body = body;

    }



    public <T> T getBodyBean(Class<T> clazz) {

        return JSON.parseObject(body.toString(), clazz);

    }

}

Copy the code

The checksum contains some data

AssertUtil.isContains(response, expectData);

Copy the code

Checking database

// check whether the query result of returnSql is equal to the expected returnDB (typeData dropped when SUCCESS is set)

JsonUtils.assertDBEquals(jdbcTemplateOfSb, returnSql, returnDB);

Copy the code

Remark:

Database validation is possible because of the JDBC database driver. JDBC stands for Java DataBase Connectivity. JDBC provides apis that allow JAVA to access relational databases, execute SQL statements, and obtain data. Common relational databases such as Oracle, MySQL, SQLServer and so on.

Well, that’s all for today. See you next time!


Not small buried quotations

1. You don’t know the meaning of persistence until you reach the top of the mountain.

2. If you can’t get over this by yourself, no one can help you out.

3. If life doesn’t make us laugh, it’s because we don’t get the joke.

4. Rivers can run into rivers, rivers can run into the sea, and the outcome is the same.

5. Memories need to be materialized.