BAEL-6246 Code for the article Send MultipartFile Request with RestAs… (#13803)

* BAEL-6246 Code for the article Send MultipartFile Request with RestAssured

* Fix code style in rest assured integration tests

---------

Co-authored-by: thibault.faure <thibault.faure@mimacom.com>
This commit is contained in:
thibaultfaure 2023-05-16 20:59:16 +02:00 committed by GitHub
parent a96f8f3e75
commit 00ca91bd58
8 changed files with 215 additions and 102 deletions

View File

@ -139,16 +139,25 @@
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>spring-mock-mvc</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-schema-validator</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>xml-path</artifactId>
<version>${rest-assured.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@ -172,8 +181,9 @@
<joda-time.version>2.9.6</joda-time.version>
<msg-simple.version>1.1</msg-simple.version>
<btf.version>1.2</btf.version>
<wiremock.version>2.4.1</wiremock.version>
<wiremock.version>2.27.2</wiremock.version>
<scribejava.version>2.5.3</scribejava.version>
<rest-assured.version>5.3.0</rest-assured.version>
</properties>
</project>

View File

@ -1,14 +1,8 @@
package com.baeldung.restassured;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
@ -16,6 +10,14 @@ import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.with;
import static org.hamcrest.Matchers.hasItems;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
public class RestAssured2IntegrationTest {
private static WireMockServer wireMockServer;
@ -24,44 +26,42 @@ public class RestAssured2IntegrationTest {
private static final String ODDS = getJson();
@BeforeClass
public static void before() throws Exception {
public static void before() {
System.out.println("Setting up!");
final int port = Util.getAvailablePort();
wireMockServer = new WireMockServer(port);
wireMockServer.start();
configureFor("localhost", port);
RestAssured.port = port;
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
stubFor(com.github.tomakehurst.wiremock.client.WireMock.get(urlEqualTo(EVENTS_PATH))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_JSON)
.withBody(ODDS)));
stubFor(post(urlEqualTo("/odds/new"))
.withRequestBody(containing("{\"price\":5.25,\"status\":1,\"ck\":13.1,\"name\":\"X\"}"))
.willReturn(aResponse().withStatus(201)));
stubFor(post(urlEqualTo("/odds/new")).withRequestBody(containing("{\"price\":5.25,\"status\":1,\"ck\":13.1,\"name\":\"X\"}"))
.willReturn(aResponse().withStatus(201)));
}
@Test
public void givenUrl_whenVerifiesOddPricesAccuratelyByStatus_thenCorrect() {
get("/odds").then().body("odds.findAll { it.status > 0 }.price",
hasItems(5.25f, 1.2f));
get("/odds").then()
.body("odds.findAll { it.status > 0 }.price", hasItems(5.25f, 1.2f));
}
@Test
public void whenRequestedPost_thenCreated() {
with().body(new Odd(5.25f, 1, 13.1f, "X"))
.when()
.request("POST", "/odds/new")
.then()
.statusCode(201);
.when()
.request("POST", "/odds/new")
.then()
.statusCode(201);
}
private static String getJson() {
return Util.inputStreamToString(RestAssured2IntegrationTest.class
.getResourceAsStream("/odds.json"));
return Util.inputStreamToString(RestAssured2IntegrationTest.class.getResourceAsStream("/odds.json"));
}
@AfterClass
public static void after() throws Exception {
public static void after() {
System.out.println("Running: tearDown");
wireMockServer.stop();
}

View File

@ -1,17 +1,7 @@
package com.baeldung.restassured;
import com.github.fge.jsonschema.SchemaVersion;
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.get;
@ -20,6 +10,17 @@ import static io.restassured.module.jsv.JsonSchemaValidatorSettings.settings;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.github.fge.jsonschema.SchemaVersion;
import com.github.fge.jsonschema.cfg.ValidationConfiguration;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
public class RestAssuredIntegrationTest {
private static WireMockServer wireMockServer;
@ -28,79 +29,79 @@ public class RestAssuredIntegrationTest {
private static final String GAME_ODDS = getEventJson();
@BeforeClass
public static void before() throws Exception {
public static void before() {
System.out.println("Setting up!");
final int port = Util.getAvailablePort();
wireMockServer = new WireMockServer(port);
wireMockServer.start();
RestAssured.port = port;
configureFor("localhost", port);
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
stubFor(com.github.tomakehurst.wiremock.client.WireMock.get(urlEqualTo(EVENTS_PATH))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_JSON)
.withBody(GAME_ODDS)));
}
@Test
public void givenUrl_whenCheckingFloatValuePasses_thenCorrect() {
get("/events?id=390").then().assertThat()
get("/events?id=390").then()
.assertThat()
.body("odd.ck", equalTo(12.2f));
}
@Test
public void givenUrl_whenSuccessOnGetsResponseAndJsonHasRequiredKV_thenCorrect() {
get("/events?id=390").then().statusCode(200).assertThat()
get("/events?id=390").then()
.statusCode(200)
.assertThat()
.body("id", equalTo("390"));
}
@Test
public void givenUrl_whenJsonResponseHasArrayWithGivenValuesUnderKey_thenCorrect() {
get("/events?id=390").then().assertThat()
get("/events?id=390").then()
.assertThat()
.body("odds.price", hasItems("1.30", "5.25", "2.70", "1.20"));
}
@Test
public void givenUrl_whenJsonResponseConformsToSchema_thenCorrect() {
get("/events?id=390").then().assertThat()
get("/events?id=390").then()
.assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json"));
}
@Test
public void givenUrl_whenValidatesResponseWithInstanceSettings_thenCorrect() {
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory
.newBuilder()
.setValidationConfiguration(
ValidationConfiguration.newBuilder()
.setDefaultVersion(SchemaVersion.DRAFTV4)
.freeze()).freeze();
JsonSchemaFactory jsonSchemaFactory = JsonSchemaFactory.newBuilder()
.setValidationConfiguration(ValidationConfiguration.newBuilder()
.setDefaultVersion(SchemaVersion.DRAFTV4)
.freeze())
.freeze();
get("/events?id=390")
.then()
get("/events?id=390").then()
.assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json").using(
jsonSchemaFactory));
.body(matchesJsonSchemaInClasspath("event_0.json").using(jsonSchemaFactory));
}
@Test
public void givenUrl_whenValidatesResponseWithStaticSettings_thenCorrect() {
get("/events?id=390")
.then()
get("/events?id=390").then()
.assertThat()
.body(matchesJsonSchemaInClasspath("event_0.json").using(
settings().with().checkedValidation(false)));
.body(matchesJsonSchemaInClasspath("event_0.json").using(settings().with()
.checkedValidation(false)));
}
@AfterClass
public static void after() throws Exception {
public static void after() {
System.out.println("Running: tearDown");
wireMockServer.stop();
}
private static String getEventJson() {
return Util.inputStreamToString(RestAssuredIntegrationTest.class
.getResourceAsStream("/event_0.json"));
return Util.inputStreamToString(RestAssuredIntegrationTest.class.getResourceAsStream("/event_0.json"));
}
}

View File

@ -0,0 +1,107 @@
package com.baeldung.restassured;
import static com.github.tomakehurst.wiremock.client.WireMock.aMultipart;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.containing;
import static com.github.tomakehurst.wiremock.client.WireMock.equalTo;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.given;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.matching.MultipartValuePatternBuilder;
import io.restassured.RestAssured;
import io.restassured.builder.MultiPartSpecBuilder;
import io.restassured.specification.MultiPartSpecification;
class RestAssuredMultipartIntegrationTest {
private WireMockServer wireMockServer;
@BeforeEach
void startServer() {
int port = Util.getAvailablePort();
wireMockServer = new WireMockServer(port);
wireMockServer.start();
configureFor("localhost", port);
RestAssured.port = port;
}
@AfterEach
void stopServer() {
wireMockServer.stop();
}
@Test
void whenUploadOneFile_ThenSuccess() throws IOException {
stubFor(post(urlEqualTo("/upload")).withHeader("Content-Type", containing("multipart/form-data"))
.withRequestBody(containing("file"))
.withRequestBody(containing(getFileContent("baeldung.txt")))
.willReturn(aResponse().withStatus(200)));
given().multiPart("file", getFile("baeldung.txt"))
.when()
.post("/upload")
.then()
.statusCode(200);
}
@Test
void whenUploadTwoFiles_ThenSuccess() throws IOException {
stubFor(post(urlEqualTo("/upload")).withHeader("Content-Type", containing("multipart/form-data"))
.withRequestBody(containing(getFileContent("baeldung.txt")))
.withRequestBody(containing(getFileContent("helloworld.txt")))
.willReturn(aResponse().withStatus(200)));
given().multiPart("file", getFile("baeldung.txt"))
.multiPart("helloworld", getFile("helloworld.txt"))
.when()
.post("/upload")
.then()
.statusCode(200);
}
@Test
void whenBuildingMultipartSpecification_ThenSuccess() {
MultipartValuePatternBuilder multipartValuePatternBuilder = aMultipart().withName("file")
.withHeader("Content-Disposition", containing("file.txt"))
.withBody(equalTo("File content"))
.withHeader("Content-Type", containing("text/plain"));
stubFor(post(urlEqualTo("/upload")).withMultipartRequestBody(multipartValuePatternBuilder)
.willReturn(aResponse().withStatus(200)));
MultiPartSpecification multiPartSpecification = new MultiPartSpecBuilder("File content".getBytes()).fileName("file.txt")
.controlName("file")
.mimeType("text/plain")
.build();
given().multiPart(multiPartSpecification)
.when()
.post("/upload")
.then()
.statusCode(200);
}
private String getFileContent(String fileName) throws IOException {
return new String(Files.readAllBytes(Paths.get(getFile(fileName).getPath())));
}
private File getFile(String fileName) throws IOException {
return new ClassPathResource(fileName).getFile();
}
}

View File

@ -1,19 +1,19 @@
package com.baeldung.restassured;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.get;
import static org.hamcrest.Matchers.hasItems;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.get;
import static io.restassured.RestAssured.port;
import static org.hamcrest.Matchers.hasItems;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
public class RestAssuredXML2IntegrationTest {
private static WireMockServer wireMockServer;
@ -23,34 +23,31 @@ public class RestAssuredXML2IntegrationTest {
private static final String TEACHERS = getXml();
@BeforeClass
public static void before() throws Exception {
public static void before() {
System.out.println("Setting up!");
final int port = Util.getAvailablePort();
wireMockServer = new WireMockServer(port);
wireMockServer.start();
RestAssured.port = port;
configureFor("localhost", port);
stubFor(get(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
stubFor(com.github.tomakehurst.wiremock.client.WireMock.get(urlEqualTo(EVENTS_PATH))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_XML)
.withBody(TEACHERS)));
}
@Test
public void givenUrl_whenVerifiesScienceTeacherFromXml_thenCorrect() {
get("/teachers")
.then()
.body("teachers.teacher.find { it.@department == 'science' }.subject",
hasItems("math", "physics"));
get("/teachers").then()
.body("teachers.teacher.find { it.@department == 'science' }.subject", hasItems("math", "physics"));
}
private static String getXml() {
return Util.inputStreamToString(RestAssuredXML2IntegrationTest.class
.getResourceAsStream("/teachers.xml"));
return Util.inputStreamToString(RestAssuredXML2IntegrationTest.class.getResourceAsStream("/teachers.xml"));
}
@AfterClass
public static void after() throws Exception {
public static void after() {
System.out.println("Running: tearDown");
wireMockServer.stop();
}

View File

@ -1,14 +1,7 @@
package com.baeldung.restassured;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.configureFor;
import static com.github.tomakehurst.wiremock.client.WireMock.post;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static io.restassured.RestAssured.post;
@ -16,6 +9,14 @@ import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.xml.HasXPath.hasXPath;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.github.tomakehurst.wiremock.WireMockServer;
import io.restassured.RestAssured;
public class RestAssuredXMLIntegrationTest {
private static WireMockServer wireMockServer;
@ -24,28 +25,30 @@ public class RestAssuredXMLIntegrationTest {
private static final String EMPLOYEES = getXml();
@BeforeClass
public static void before() throws Exception {
public static void before() {
System.out.println("Setting up!");
final int port = Util.getAvailablePort();
wireMockServer = new WireMockServer(port);
wireMockServer.start();
configureFor("localhost", port);
RestAssured.port = port;
stubFor(post(urlEqualTo(EVENTS_PATH)).willReturn(
aResponse().withStatus(200)
stubFor(com.github.tomakehurst.wiremock.client.WireMock.post(urlEqualTo(EVENTS_PATH))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type", APPLICATION_XML)
.withBody(EMPLOYEES)));
}
@Test
public void givenUrl_whenXmlResponseValueTestsEqual_thenCorrect() {
post("/employees").then().assertThat()
post("/employees").then()
.assertThat()
.body("employees.employee.first-name", equalTo("Jane"));
}
@Test
public void givenUrl_whenMultipleXmlValuesTestEqual_thenCorrect() {
post("/employees").then().assertThat()
post("/employees").then()
.assertThat()
.body("employees.employee.first-name", equalTo("Jane"))
.body("employees.employee.last-name", equalTo("Daisy"))
.body("employees.employee.sex", equalTo("f"));
@ -53,38 +56,31 @@ public class RestAssuredXMLIntegrationTest {
@Test
public void givenUrl_whenMultipleXmlValuesTestEqualInShortHand_thenCorrect() {
post("/employees")
.then()
post("/employees").then()
.assertThat()
.body("employees.employee.first-name", equalTo("Jane"),
"employees.employee.last-name", equalTo("Daisy"),
"employees.employee.sex", equalTo("f"));
.body("employees.employee.first-name", equalTo("Jane"), "employees.employee.last-name", equalTo("Daisy"), "employees.employee.sex", equalTo("f"));
}
@Test
public void givenUrl_whenValidatesXmlUsingXpath_thenCorrect() {
post("/employees")
.then()
post("/employees").then()
.assertThat()
.body(hasXPath("/employees/employee/first-name",
containsString("Ja")));
.body(hasXPath("/employees/employee/first-name", containsString("Ja")));
}
@Test
public void givenUrl_whenValidatesXmlUsingXpath2_thenCorrect() {
post("/employees")
.then()
post("/employees").then()
.assertThat()
.body(hasXPath("/employees/employee/first-name[text()='Jane']"));
}
private static String getXml() {
return Util
.inputStreamToString(RestAssuredXMLIntegrationTest.class.getResourceAsStream("/employees.xml"));
return Util.inputStreamToString(RestAssuredXMLIntegrationTest.class.getResourceAsStream("/employees.xml"));
}
@AfterClass
public static void after() throws Exception {
public static void after() {
System.out.println("Running: tearDown");
wireMockServer.stop();
}

View File

@ -0,0 +1 @@
baeldung

View File

@ -0,0 +1 @@
hello world