08-21 企业微信接口测试实战 一

课堂PPT

PPT地址

接口

  • 有输入参数和输出内容的一套有逻辑处理单元

企业微信

https://developer.work.weixin.qq.com/document/path/90664

pom


    <properties>
        <maven.compiler.encoding>UTF-8</maven.compiler.encoding>
        <!-- 使用 Java 11 语言特性 ( -source 11 ) 并且还希望编译后的类与 JVM 11 ( -target 11 )兼容,
        可以添加以下两个属性,它们是默认属性插件参数的名称 -->
        <java.version>11</java.version>
        <!-- 对应junit Jupiter的版本号;放在这里就不需要在每个依赖里面写版本号,导致对应版本号会冲突 -->
        <junit.jupiter.version>5.8.2</junit.jupiter.version>
        <!-- maven-plugins -->
        <maven.compiler.version>3.8.1</maven.compiler.version>
        <maven-surefire-plugin.version>3.0.0-M5</maven-surefire-plugin.version>
        <!-- 断言 -->
        <hamcrest.version>2.2</hamcrest.version>
        <!-- log日志 -->
        <slf4j.version>2.0.0-alpha7</slf4j.version>
        <logback.version>1.3.0-alpha16</logback.version>
        <!-- allure报告 -->
        <allure.version>2.18.1</allure.version>
        <aspectj.version>1.9.9.1</aspectj.version>
        <allure-maven.version>2.10.0</allure-maven.version>
        <allure.cmd.download.url>
            https://repo.maven.apache.org/maven2/io/qameta/allure/allure-commandline
        </allure.cmd.download.url>
        <!-- faker -->
        <javafaker.version>1.0.2</javafaker.version>
        <!-- selenium -->
        <selenium.version>4.3.0</selenium.version>
        <!-- appium -->
        <appium.version>8.1.1</appium.version>
        <!-- rest-assured -->
        <rest-assured.version>5.1.1</rest-assured.version>
        <!-- fasterjson -->
        <jackson.version>2.13.1</jackson.version>
        <!-- apache-commonio -->
        <commonio.version>2.11.0</commonio.version>
    </properties>
    <!--    物料清单 (BOM)-->
    <dependencyManagement>
        <dependencies>
            <!--当使用 Gradle 或 Maven 引用多个 JUnit 工件时,此物料清单 POM 可用于简化依赖项管理。不再需要在添加依赖时设置版本-->
            <dependency>
                <groupId>org.junit</groupId>
                <artifactId>junit-bom</artifactId>
                <version>${junit.jupiter.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.google.guava</groupId>
                <artifactId>guava</artifactId>
                <version>31.0.1-jre</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <repositories>
        <repository>
            <id>jitpack.io</id>
            <url>https://jitpack.io</url>
        </repository>
    </repositories>

    <dependencies>
        <!--junit5-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <!--对应添加的依赖的作用范围-->
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.platform</groupId>
            <artifactId>junit-platform-suite</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.vintage</groupId>
            <artifactId>junit-vintage-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <!--hamcrest断言-->
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest</artifactId>
            <version>${hamcrest.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>${hamcrest.version}</version>
            <scope>test</scope>
        </dependency>
        <!--faster json解析yaml文件 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-yaml</artifactId>
            <version>${jackson.version}</version>
            <scope>compile</scope>
        </dependency>
        <!--        csv文件解析-->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-csv</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <!-- log日志 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>${logback.version}</version>
        </dependency>

        <!-- common io-->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commonio.version}</version>
        </dependency>
        <!-- allure-->
        <dependency>
            <groupId>io.qameta.allure</groupId>
            <artifactId>allure-junit5</artifactId>
            <version>${allure.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>${aspectj.version}</version>
            <scope>runtime</scope>
        </dependency>
        <!--  随机测试数据生成库  -->
        <dependency>
            <groupId>com.github.javafaker</groupId>
            <artifactId>javafaker</artifactId>
            <version>${javafaker.version}</version>
        </dependency>
        <!-- selenium-->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>${selenium.version}</version>
            <scope>compile</scope>
        </dependency>
        <!-- appium -->
        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>${appium.version}</version>
            <scope>compile</scope>
        </dependency>
        <!-- rest-assured -->
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>${rest-assured.version}</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>io.rest-assured</groupId>
            <artifactId>json-schema-validator</artifactId>
            <version>${rest-assured.version}</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>${maven-surefire-plugin.version}</version>
                <configuration>
                    <argLine>
                        -javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
                    </argLine>
                    <includes>
                        <include>**/*Test</include>
                    </includes>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.junit.jupiter</groupId>
                        <artifactId>junit-jupiter-engine</artifactId>
                        <version>${junit.jupiter.version}</version>
                    </dependency>
                    <dependency>
                        <groupId>org.junit.vintage</groupId>
                        <artifactId>junit-vintage-engine</artifactId>
                        <version>${junit.jupiter.version}</version>
                    </dependency>
                </dependencies>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.version}</version>
                <configuration>
                    <parameters>true</parameters>
                    <!-- 设置jre版本为 11 -->
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <!-- 设置编码为 UTF-8 -->
                    <encoding>${maven.compiler.encoding}</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>io.qameta.allure</groupId>
                <artifactId>allure-maven</artifactId>
                <version>${allure-maven.version}</version>
                <configuration>
                    <reportVersion>${allure.version}</reportVersion>
                    <allureDownloadUrl>${allure.cmd.download.url}/${allure.version}/allure-commandline-${allure.version}.zip</allureDownloadUrl>
                </configuration>
            </plugin>
        </plugins>
    </build>

json Schema

json viewer

gpath验证

https://onecompiler.com/groovy/3xxb42jsb

import groovy.json.JsonSlurper

def jsonSlurper = new JsonSlurper()
def one = jsonSlurper.parseText('{"errcode":0,"errmsg":"ok","department":[{"id":1,"name":"产研部","parentid":0,"order":100000000,"department_leader":[]},{"id":2,"name":"质量控制部","parentid":1,"order":100000000,"department_leader":[]},{"id":3,"name":"产品部","parentid":1,"order":99999000,"department_leader":[]},{"id":4,"name":"后端研发部","parentid":1,"order":99998000,"department_leader":[]},{"id":5,"name":"前端部门","parentid":1,"order":99997000,"department_leader":[]},{"id":6,"name":"测试一组1","parentid":2,"order":100000000,"department_leader":[]},{"id":7,"name":"测试二组2","parentid":2,"order":99999000,"department_leader":[]},{"id":8,"name":"刘越彬1648352111146","parentid":1,"order":475,"department_leader":[]},{"id":9,"name":"孙雨泽1648352112153","parentid":1,"order":771,"department_leader":[]},{"id":10,"name":"徐煜城1648352112988","parentid":1,"order":321,"department_leader":[]},{"id":11,"name":"戴鹭洋1648352113646","parentid":1,"order":901,"department_leader":[]},{"id":12,"name":"熊明1648352114249","parentid":1,"order":547,"department_leader":[]},{"id":13,"name":"田建辉1648352114899","parentid":1,"order":75,"department_leader":[]},{"id":14,"name":"梁健雄1648352115509","parentid":1,"order":521,"department_leader":[]}]}')


println(one)


def id = one.department.findAll{ it.order < 1000}.id

println(id)

作业

https://developer.work.weixin.qq.com/document/path/95350

  • 部门相关用例补全
    • 查找部门用json schema模版断言
    • 查找部门的时候找出来id < 100的所有部门的 order 为list
  • 命令行运行并生成allure报告

获取token

https://developer.work.weixin.qq.com/document/path/91039

创建部门

https://developer.work.weixin.qq.com/document/path/90205


获取token正常,创建部门报这个错,不知道啥情况

package com.ceshiren;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import java.util.HashMap;

import static io.restassured.RestAssured.given;
import static io.restassured.path.json.JsonPath.from;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.jupiter.api.Assertions.assertAll;

public class DepartmentTest {
    static String token;

    @BeforeAll
    static void beforeAll(){
        token = getToken();

    }

    @Test
    void createDep(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("name", "研发中心");
        map.put("name_en", "RDGZ");
        map.put("parentid", 1);
        map.put("order", 1);
        map.put("id", 2);

        String resq = given()
                .proxy(8888)
                .relaxedHTTPSValidation()
                .contentType("application/json")
                .queryParam("access_token", token)
                .body(map)
                .when()
                .post("https://qyapi.weixin.qq.com/cgi-bin/department/create")
                .then().log().all().extract().body().asString();

        String errmsg = from(resq).getString("errmsg");
        String errcode = from(resq).getString("errcode");

        assertAll("",
                ()->assertThat(errcode, equalTo(0)),
                ()->assertThat(errmsg, equalTo("created")));

    }



    static String getToken(){
        String resq = given()
                .params("corpid", "wwcfe098d283011b8a", "corpsecret", "8I9FBESpaLBtRBf592lZmrcU6zPd9lB-5PKJtpbN0DY")
                .when()
//                .get("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wwcfe098d283011b8a&corpsecret=8I9FBESpaLBtRBf592lZmrcU6zPd9lB-5PKJtpbN0DY")
                .get("https://qyapi.weixin.qq.com/cgi-bin/gettoken")
                .then().statusCode(200).extract().body().asString();

        String accessToken = from(resq).getString("access_token");
        System.out.println(accessToken);
        return accessToken;
    }
}

package Interface;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class qiyeweixinTest {

//获取access_token
@Test
void getToken(){
    RestAssured.useRelaxedHTTPSValidation();
    String tokenUrl="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww8e162735dca7d060&corpsecret=GTfz5wtzefJQs7N-dROcRl1h-6PCdQxNRBHKQvelZIU";
    String access_token = given()
            .when()
            .get(tokenUrl)
            .then()
            .log().all()
            .extract().path("access_token");
    System.out.println("获取到的access_token为:"+access_token);
}
//创建部门
@Test
void creatDepartment() throws IOException {
    RestAssured.useRelaxedHTTPSValidation();
    String DepartmentUrl="https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=sAekNubf-byd1J3VwYYgLom80pgORXpgI_k05whOhbQHB3FwaXw_CCMjQ3EqB8CBq_MxaOK2kAzJrzLhxHc2xYyKHuOORul-K4viNBVHpxPk3H_KmVj9ItZKWIxisLHuHXD4ZMo76yLdIOdZtCeGnHmPhxt0qvNy2X5a0Kghhp0ITsCdA3moGnBDTOvNabNVgH5_860RLYIf1yTld-ii-w";
    //读取json文件获取请求信息
    ObjectMapper mapper = new ObjectMapper(new JsonFactory());
    TypeReference<HashMap<String, Object>> typeReference = new TypeReference<HashMap<String, Object>>() {
    };
    mapper.findAndRegisterModules();
    HashMap<String, Object> hashMapList =
            mapper.readValue(new File("src/test/resources/Department.json"), typeReference);
    System.out.println(hashMapList.toString());
    //发起创建请求
    String errmsg = given()
            .contentType("application/json")
            .body(hashMapList)
            .log().all()
            .when()
            .post(DepartmentUrl)
            .then()
            .log().all()
            .extract().path("errmsg");
    //断言是否创建成功
    assertEquals("created",errmsg);

}

}

image
正常了

作业

部门

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class AddDepartWithJsonTest {
    static String token;
    static Integer id;

    @BeforeAll
    public static void getToken() {
        Response response = given().log().all()
                .queryParam("corpid", "wwa9838ed5429d61e4")
                .queryParam("corpsecret", "RREDkaDuRE4Ixye14Pkvt4k5Nj1uEHvPZUZOyMvAJdM")
                .when()
                .get("https://qyapi.weixin.qq.com/cgi-bin/gettoken")
                .then()
                .log().all()
                .statusCode(200)
                .extract().response();
        token = response.path("access_token").toString();
        System.out.println(token);
    }

    /*
     * 创建部门
     * */
    @Test
    @Order(1)
    public void createDepartment() {
        String name = "name" + FakerUtil.get_name();
        String body = "{\n" +
                "    \"name\": \"" + name + "\",\n" +
                "    \"parentid\": 1\n" +
                "}";
        Response response = given().log().all()
                .contentType("application/json")
                .body(body)
                .when()
                .post("https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=" + token)
                .then().log().all()
                .extract().response();
        Integer errcode = response.path("errcode");
//        assertEquals(0, errcode);
        String errmsg = response.path("errmsg");
//        assertEquals("created", errmsg);
        id = response.path("id");
        System.out.println("id" + id);
    }

    /*
     * 修改部门
     * */
    @Test
    @Order(2)
    public void updateDepartment() {
        String name = "name" + FakerUtil.get_name();
        String body = "{\n" +
                "    \"name\": \"" + name + "\",\n" +
                "    \"name_en\": \"child01\",\n" +
                "    \"id\": " + id + "\n" +
                "}";
        Response response = given().log().all()
                .contentType("application/json")
                .body(body)
                .when()
                .post("https://qyapi.weixin.qq.com/cgi-bin/department/update?access_token=" + token)
                .then()
                .statusCode(200)
                .extract().response();
        String errcode = response.path("errcode").toString();
        System.out.println("response" + errcode);
        assertEquals("0", errcode);
    }

    /*
     * 获取部门列表
     * */
    @Test
    @Order(3)
    public void listDepartment() {
        Response response = given().log().all()
                .queryParam("access_token", token)
//                .queryParam("id", id)
                .when()
                .get("https://qyapi.weixin.qq.com/cgi-bin/department/simplelist")
                .then()
                .log().all()
                .extract().response();
        String errcode = response.path("errcode").toString();
        assertEquals("0", errcode);
    }

    /*
     * 删除部门
     * */
    @Test
    @Order(4)
    public void deleteDepartment() {
        Response response = given().log().all()
                .queryParam("access_token", token)
                .queryParam("id", id)
                .when()
                .get("https://qyapi.weixin.qq.com/cgi-bin/department/delete")
                .then()
                .log().all()
                .extract().response();
        String errcode = response.path("errcode").toString();
        assertEquals("0", errcode);
    }
}

schema断言

public class TestJsonSchema {
    static String token;

    @BeforeAll
    public static void getToken() {
        Response response = given().log().all()
                .queryParam("corpid", "wwa9838ed5429d61e4")
                .queryParam("corpsecret", "RREDkaDuRE4Ixye14Pkvt4k5Nj1uEHvPZUZOyMvAJdM")
                .when()
                .get("https://qyapi.weixin.qq.com/cgi-bin/gettoken")
                .then()
                .log().all()
                .statusCode(200)
                .extract().response();
        token = response.path("access_token").toString();
        System.out.println(token);
    }

    @Test
    void testJsonSchema() {
        given().log().all()
                .queryParam("access_token", token)
                .when()
                .get("https://qyapi.weixin.qq.com/cgi-bin/department/simplelist")
                .then()
                .log().all()
                .assertThat()
                .body(matchesJsonSchemaInClasspath("schema.json"));
    }
}

成员

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class MemberTest {
    static String token;

    @BeforeAll
    public static void getToken() {
        Response response = given().log().all()
                .queryParam("corpid", "wwa9838ed5429d61e4")
                .queryParam("corpsecret", "RREDkaDuRE4Ixye14Pkvt4k5Nj1uEHvPZUZOyMvAJdM")
                .when()
                .get("https://qyapi.weixin.qq.com/cgi-bin/gettoken")
                .then()
                .log().all()
                .statusCode(200)
                .extract().response();
        token = response.path("access_token").toString();
        System.out.println(token);
    }

    /*
     * 创建成员
     * */
    @Test
    @Order(1)
    public void createMember() throws IOException {
        // 解析文件类型声明
        ObjectMapper objectMapper = new ObjectMapper(new JsonFactory());
        // 要解析的类型
        TypeReference<HashMap<String, Object>> typeReference = new TypeReference<HashMap<String, Object>>() {
        };
        HashMap<String, Object> memberBody = objectMapper.readValue(new File("src/test/resources/member.json"), typeReference);
        System.out.println("memberBody" + memberBody);

        given().log().all()
                .contentType("application/json")
                .queryParam("access_token", token)
                .body(memberBody)
                .when()
                .post("https://qyapi.weixin.qq.com/cgi-bin/user/create")
                .then().log().all()
                .statusCode(200);
    }

    /*
     * 创建成员     还没写完
     * */
    @Test
    @Order(2)
    public void updateMember() {


        given().log().all()
                .contentType("application/json")
                .queryParam("access_token", token)
                .body("")
                .when()
                .post("https://qyapi.weixin.qq.com/cgi-bin/user/update")
                .then().log().all()
                .statusCode(200);
    }

    /*
     * 读取成员
     * */
    @Test
    @Order(3)
    public void getMember() {


        given().log().all()
                .queryParam("access_token", token)
                .queryParam("userid", 1)
                .when()
                .get("https://qyapi.weixin.qq.com/cgi-bin/user/get")
                .then().log().all()
                .statusCode(200);
    }

    /*
     * 删除成员
     * */
    @Test
    @Order(4)
    public void deleteMember() {


        given().log().all()
                .queryParam("access_token", token)
                .queryParam("userid", 1)
                .when()
                .get("https://qyapi.weixin.qq.com/cgi-bin/user/delete")
                .then().log().all()
                .statusCode(200);
    }
}

课堂练习:
第一步:获取接口鉴权access_token
package com.hogwarts.base.login;

import static io.restassured.RestAssured.given;
import static io.restassured.specification.ProxySpecification.host;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TokenTest {

//access_token接口的请求参数
public static String corpid = "wwce12cbff5ba4fdba";

//access_token接口的请求参数
public static String secret = "JnSJm5xRS9yYcd9zOycHkQ3_tkfIAZ3GRUx2ZZxkCjM";

//创建部门接口接受的鉴权access_token
public static String access_token;

//声明日志
public static Logger logger = LoggerFactory.getLogger(TokenTest.class);

@BeforeAll
public static void tokenTestInit (){

    //设置本地代理
    //配置本地代理信息
    RestAssured.proxy = host("127.0.0.1").withPort(7777);
    //忽略HTTP检验
    RestAssured.useRelaxedHTTPSValidation();

    //获取accuess_token
    Response response = given()
                                .param("corpid",corpid)
                                .param("corpsecret",secret)
                                .log().headers()
                            .when()
                                .get("https://qyapi.weixin.qq.com/cgi-bin/gettoken")
                            .then()
                                .log().all()
                                .statusCode(200)//对http请求的状态码进行校验,正常code值:200
                                .extract()
                                .response();

    access_token = response.path("access_token").toString();

    logger.info("access_token的值:" + access_token);
}

}

//第二步:读取json文件的测试数据并做参数化,发起接口请求创建一级子部门
package com.hogwarts.base.contacts;

import com.hogwarts.base.login.TokenTest;
import com.hogwarts.utils.FakerUtil;
import com.hogwarts.utils.MapperUtil;
import io.restassured.response.Response;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertAll;

public class CreateDepartmentWithJsonTest extends TokenTest {

//声明日志
public static Logger logger = LoggerFactory.getLogger(CreateDepartmentWithJsonTest.class);

//存储新创建的一级部门编号
public static List<Integer> deptIdList = new ArrayList<>();

@AfterAll
public static void createDeptWithJsonTearDown(){
    //查看已创建的一级部门编号
    deptIdList.forEach((num)-> System.out.println("已添加的部门编号: " + num));
}

//读取json文件并对测试数据做参数化,发起接口请求创建一级子部门
@Test
public void createOneLevelDept_mapMapperUtil_fakerUtil_Test(){
    
    //准备请求体数据
    //创建hashmap存储测试数据
    HashMap<String, Object> deptBody = new HashMap<>();

    //调用读取外置文件的工具类,传入用什么格式读取文件
    MapperUtil<HashMap<String, Object>> mapMapperUtil = new MapperUtil<>();

    //读取指定路径的文件
    HashMap<String,Object> deptData = mapMapperUtil.getReadValue("D:\\hogwarts\\teachAPI\\api-WeCom\\src\\test\\resources\\createDept_parentid_params1.json");

    logger.debug("deptData: " + deptData);

    //读取到json文件中的数据的格式
    //deaprtBody:{"name": "${deptName}","parentid": 1,"order": "${orderNumber}"}
    deptData.forEach((str,obj)->{//${deptName},${orderNumber}
        //转换字符串
        String value = obj.toString();
        //测试数据包含特殊符号
        if(value.startsWith("${") && value.endsWith("}")){
            //保留请求参数即可,其他特殊符号都去除
            String s1 = StringUtils.stripStart(value, "${");//deptName}
            String s2 = StringUtils.stripEnd(s1, "}");//deptName
            //请求参数赋值
            if("deptName".equals(s2)){
                obj = FakerUtil.get_name() + FakerUtil.get_zh_phone();
            }else if("orderNumber".equals(s2)){
                obj = FakerUtil.getNum(10, 30);
            }else if("deptId".equals(s2)){
                obj = FakerUtil.getNum(2,20);
            }
        }
        //存储新的请求体数据
        deptBody.put(str,obj);
    });

    logger.debug("deptBody: " + deptBody);

    //发送创建一级子部门的请求
    Response response = given()
                                .contentType("application/json;charset=UTF-8")
                                .queryParam("access_token",access_token)
                                .body(deptBody)
                            .when()
                                .post("https://qyapi.weixin.qq.com/cgi-bin/department/create")
                            .then()
                                .log().all()
                                .statusCode(200)
                                .extract()
                                .response();

    logger.info("创建一级子部门的实际结果,response_errcode的状态码: " + response.path("errcode"));
    logger.info("创建一级子部门的实际结果,errmsg的值: " + response.path("errmsg"));
    logger.info("创建一级子部门的实际结果,id的值: " + response.path("id"));

    //获取一级子部门id
    Integer id = (Integer) deptBody.get("id");
    //存储一级子部门编号
    deptIdList.add(id);

    //多断言
    assertAll("测试创建一级子部门失败",
            ()-> assertThat("errcode值错误",response.path("errcode"),is(equalTo(0))),
            ()->assertThat("errmsg值错误",response.path("errmsg"),is(equalTo("created"))),
            ()->assertThat("id值错误",response.path("id"),is(equalTo(id)))
    );
}

}

idea控制台输出测试用例执行创建一级子部门的实际结果

回家作业:

  • 部门相关用例补全
    • 查找部门用json schema模版断言
    • 查找部门的时候找出来id < 100的所有部门的 order 为list

package com.hogwarts.base.contacts;

import com.hogwarts.base.login.TokenTest;
import io.qameta.allure.Step;
import io.restassured.response.Response;
import jdk.jfr.Description;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.stream.Stream;
import static io.restassured.RestAssured.given;
import static io.restassured.module.jsv.JsonSchemaValidator.matchesJsonSchemaInClasspath;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.params.ParameterizedTest.ARGUMENTS_WITH_NAMES_PLACEHOLDER;

@DisplayName(“获取子部门ID列表”)
public class QueryDeptIdListTest extends TokenTest {

//声明日志
public static Logger logger = LoggerFactory.getLogger(QueryDeptIdListTest.class);

@DisplayName("正向-根据部门ID,调用查询接口获取此部门的ID列表")
@Step("interface query deptIdList by DeptId")
@ParameterizedTest(name=ARGUMENTS_WITH_NAMES_PLACEHOLDER)
@Description("获取鉴权,调用接口创建部门,根据此部门ID,调用查询接口获取此部门ID列表")
@MethodSource("queryDeptIdListByDeptId_params")
public void queryDeptIdListByDeptIdTest(Integer id){
    //发起get请求
    Response response = given()
                                .param("access_token", access_token)
                                .param("id", id)
                            .when()
                                .get("https://qyapi.weixin.qq.com/cgi-bin/department/simplelist")
                            .then()
                                .log().all()
                                .body(matchesJsonSchemaInClasspath("queryDeptIdListByDeptId.json"))
                                .extract()
                                .response();

    Integer deptId = response.path("department_id[0].id");
    Integer errcode = response.path("errcode");
    String  errmsg = response.path("errmsg");

    logger.info("newDept_id的值: " + deptId);
    logger.info("errcode的值: " + errcode);
    logger.info("errmsg的值: " + errmsg);

    assertAll("根据部门ID,获取此部门ID列表的测试失败",
            ()->assertThat("deptId的值",deptId,is(equalTo(id))),
            ()->assertThat("errcode的值",errcode,is(equalTo(0))),
            ()->assertThat("errmsg的值",errmsg,is(equalTo("ok")))
    );
}

static Stream<Integer> queryDeptIdListByDeptId_params(){
    //创建一级部门
    new CreateDepartmentWithJsonTest().createOneLevelDept_mapMapperUtil_fakerUtil_Test();

    return CreateDepartmentWithJsonTest.deptIdList.stream();
}


@DisplayName("正向-调用接口获取全量的部门ID列表")
@Step("interface query allDeptIdList")
@Description("获取鉴权,调用接口创建部门,调用查询接口获取全量的部门ID列表,用jsonSchema模板断言")
@Test
public void queryAllDeptIdList_jsonSchema_Test(){
    //发起get请求
    given()
                .param("access_token",access_token)
                .param("id","")
            .when()
                .get("https://qyapi.weixin.qq.com/cgi-bin/department/simplelist")
            .then()
                .log().all()
                .body(matchesJsonSchemaInClasspath("queryAllDeptIdTest_jsonSchema.json"));
}

@DisplayName("正向-调用接口获取id<100的所有部门的order为list")
@Step("interface query id<100 deptOrderList")
@Description("获取鉴权,调用接口创建部门,调用查询接口获取id<100的所有部门的order list")
@Test
public void queryDeptOrderList_gpath_Test(){

    //发起get请求
    Response response = given()
                                .param("access_token",access_token)
                                .param("id","")
                            .when()
                                .get("https://qyapi.weixin.qq.com/cgi-bin/department/simplelist")
                            .then()
                                .log().all()
                                .body(matchesJsonSchemaInClasspath("queryDeptOrderList_gpath.json"))
                                .extract().response();

    //获取id<100的子部门order list
    List<Integer> deptOrderList = response.path("department_id.findAll{it.id<100}.order");

    logger.info("id小于100的所有部门的order list: " + deptOrderList);
    deptOrderList.forEach(order-> System.out.println("id小于100的所有部门的order: " + order));

}

}