本文转自测试人社区,原文链接: https://ceshiren.com/t/topic/28419

目录

  • 文件上传接口场景
  • 如何通过接口上传文件

文件上传接口场景

  • Content-Type 类型
  • multipart/form-data

软件测试学习笔记丨接口请求体-文件_上传

REST-assured 上传文件

  • 创建本地文件
  • hogwarts.txt
  • 调用方法
  • multiPart()
  • 参数:String name
  • 参数:File file
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import java.io.File;
import static io.restassured.RestAssured.given;
import static io.restassured.specification.ProxySpecification.host;

public class TestMultiPart {

    @Test
    void testUploadFile(){

        // 需要上传的文件对象
        File myFile = new File("src/test/resources/hogwarts.txt");

        // 定义一个代理的配置信息
        RestAssured.proxy = host("localhost").withPort(8888);
        // 忽略HTTPS校验
        RestAssured.useRelaxedHTTPSValidation();

        given()
            .multiPart("hogwarts", myFile)  // 传递文件对象
            .log().headers()  // 打印请求消息头
            .log().body()  // 打印请求消息体
        .when()
            .post("https://httpbin.ceshiren.com/post")  //发送POST请求
        .then()
            .statusCode(200);  // 响应断言
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.

REST-assured 上传文件

  • 携带多种数据
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import java.io.File;
import static io.restassured.RestAssured.given;
import static io.restassured.specification.ProxySpecification.host;

public class TestMultiParts {

    @Test
    void testUploadFiles(){

        // 需要上传的文件对象
        File myFile = new File("src/test/resources/hogwarts.txt");

        // 定义一个代理的配置信息
        RestAssured.proxy = host("localhost").withPort(8888);
        // 忽略HTTPS校验
        RestAssured.useRelaxedHTTPSValidation();

        given()
            .multiPart("hogwarts", myFile)  // 传递文件对象
            .multiPart("ceshiren", "{"hogwarts": 666}",
             "application/json")  // 传递JSON数据
            .log().headers()  // 打印请求消息头
            .log().body()  // 打印请求消息体
        .when()
            .post("https://httpbin.ceshiren.com/post")  // 发送POST请求
        .then()
            .statusCode(200);  // 响应断言
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.