Upload files using Rest Assured

Rest Assured has the capability to test the service that takes a file as an input and upload it to the server or cloud storage. It could be any kind of file like text data, image, etc. The different extensions of image like JPEG, JPG, PNG, etc. are also supported to test.

Rest Assured has provided the capability through ‘multiPart()’ method which could be used to upload the files.

Let’s see how to upload the file and validate its response.

 

1. Specify the location of the file

File uploadFile = new File("C:\\temp\\testfile.png"); 

Here the object “uploadFile” of type file is created, the address of which is specified above.

 

2. Set up a request with the specified base URI

 RestAssured.baseURI = "https://petstore.swagger.io/v2/pet/1";

Base URI is the root address of the Resource. Here we are specifying to REST assured to use the above as the base URI of the service.

 

3. Specify the exact resource and upload file using .multiPart() function available in Rest Assured.

RestAssured.given()

.multiPart(uploadFile)


.when()

.post("/uploadImage");
 

Here file is uploaded using the multiPart method with the POST call to the exact resource which is “/uploadImage” in this case. Thus, the complete URL would be “https://petstore.swagger.io/v2/pet/1/uploadImage” to which we are sending a GET request.

 

4. Response Validation

1. Validation of Status code

  .then().assertThat().statusCode(200);

Since it is a GET request for which we are making a call, thus the expected status code would be 200. Here, we are validating the response based on the condition where if status code from the response matches with the value 200.

2. Validation of Response Body

 .then().assertThat().body(message, contain("File uploaded"));

Here we are comparing the response message of the body with it’s expected result in the assert statement. If the actual result matched with expected, then assert return true else false.

 

Complete Example Code
@Test
public void uploadFile() {

//Specify your own location and file

File testUploadFile = new File("C:\\temp\\testfile.png");

RestAssured.baseURI = "https://petstore.swagger.io/v2/pet/1";

RestAssured.given()

.multiPart(testUploadFile)

.when()

.post("/uploadImage");

.then().assertThat().statusCode(200);

}