Test Web API with junit

Test the Web API using jUnit and rest-assured

I need to test the API that uses the JSON format, so I will summarize it below. I'm verifying it, so I think there are some mistakes.

Things necessary

Request settings

rest-assured will automatically convert the Object class used for the request to Json. This time I'm using Jackson 2.

--The existence of the classpath is confirmed and serialization is performed in the following order.

  1. Jackson2
  2. Jackson
  3. Gson

Since ObjectMapper is used, specify its settings and connection destination.

//api connection destination host name
RestAssured.baseURI = "http://localhost"
//ObjectMapper settings
RestAssured.config = RestAssuredConfig.config().objectMapperConfig(
        ObjectMapperConfig.objectMapperConfig().jackson2ObjectMapperFactory(new Jackson2ObjectMapperFactory() {
            @SuppressWarnings("rawtypes")
            @Override
            public ObjectMapper create(Class cls, String charset) {
                ObjectMapper objectMapper = new ObjectMapper();
                //ObjectMapper settings here

                return objectMapper;
            }
        })
);

Send request

//static import
import static io.restassured.RestAssured.given;

ResponseClass response = given()
    .contentType(ContentType.JSON)  // content type
    .body(reqest)                   //request
.when()
    .post("/api/hoge/1")                 //Specify API endpoint
.then()
    .statusCode(200)
    .extract().as(ResponseClass.class);   //Deserialize to specified class

Response assertion

Use junit assert to see if the expected value is returned.

Assert.assertThat(response.hoge, is("hoge"));

Record match confirmation using DbUnit and Excel

If you use DbUnit, you can compare the current DB record and the data written to Excel as the expected value. It is also convenient because you can write DB records to an Excel file.

Connection connection = DriverManager.getConnection(url, username, password)
IDatabaseConnection iDbConnection = new IDatabaseConnection(connection);

//Data after execution
IDataSet dataSet = dbConn.createDataSet();

//Get the record with the specified table name
ITable data= dataSet.getTable("table");

//Set columns you want to exclude from assert
data = DefaultColumnFilter.excludedColumnsTable(iTable, "created_at");

//Sort by column
data= new SortedTable(iTable, "hoge_name");


//Expected value data(Excel)
ITable Expected Value= new XlsDataSet(new File("hoge/huga/Expected value.xls"));
Expected value= DefaultColumnFilter.excludedColumnsTable(iTable, "created_at");
Expected value= new SortedTable(iTable, "hoge_name");

//DbUnit Assertion, not junit assertEquals#Be careful to use assertEquals
Assertion.assertEquals(Expected value, data);

I want to include values of different types in request parameters

--After converting the request Object to Map using ObjectMapper, specify the json key and put any parameter to map.

//Convert request object to MAP
RequestObj request = new RequestObj():
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(request);
LinkedHashMap<String, Object> map = objectMapper.readValue(jsonString, new TypeReference<LinkedHashMap<String, Object>>(){});

//Any key:set value
map.put("dinner", "Grilled meat")

//Convert map to String
String jsonString = objectMapper.writeValueAsString(map);

//Set json string to body and send request
ResponseClass response  = given()
                .contentType(ContentType.JSON)
                .body(jsonString)
                .log().body()
            .when()
                .post(endpoint)
            .then()
                .log().body()
                .statusCode(200)
                .extract().as(responseClass);

Recommended Posts

Test Web API with junit
Unit test with Junit.
REST API test with REST Assured Part 2
[Java] Test private methods with JUnit
Test Spring framework controller with Junit
Control test order in Junit4 with enumeration
How to test private scope with JUnit
JUnit 5 gradle test fails with lombok annotation
Java automated test implementation with JUnit 5 + Gradle
Java automated test implementation with JUnit 5 + Apache Maven
How to test interrupts during Thread.sleep with JUnit
Easy JUnit test of Elasticsearch 2018 version with embedded-elasticsearch
Test code using mock with JUnit (EasyMock center)
Create a web api server with spring boot
Mixin test cases with JUnit 5 and default methods
Compatible with Android 10 (API 29)
Try JUnit test launch
Integration Test with Gradle
Web application test automation
[Rails] Test with RSpec
Test Nokogiri with Rspec.
Automatically test with Gauge
Load test with JMeter
Test the contents of an Excel file with JUnit
[JUnit 5 compatible] Write a test using JUnit 5 with Spring boot 2.2, 2.3
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
WebAPI unit test and integration test with SpringBoot + Junit5, 4 patterns
I wrote a test with Spring Boot + JUnit 5 now
[Java] JUnit4 test case example
Create XML-RPC API with Wicket
JUnit 5 fails with java.lang.NoSuchMethodError: org.junit.platform.launcher.Launcher.execute
Use Bulk API with RestHighLevelClient
Test Active Strage with RSpec
API creation with Rails + GraphQL
Test private methods in JUnit
JUnit assertions and Matcher API
Remote debugging with Gradle test
Test GraphQL resolver with rspec
Test private methods in JUnit
Isn't Web API too convenient? ?? ??
REST API testing with REST Assured
[JUnit] Test the thrown exception
Web application built with docker (1)
Link API with Spring + Vue.js
Easy web scraping with Jsoup
UnitTest with SpringBoot + JUnit + Mockito
[Java] I want to test standard input & standard output with JUnit
Implement a simple Web REST API server with Spring Boot + MySQL
Get Flux result of Spring Web Flux from JS with Fetch API
Automatic API testing with Selenium + REST-Assured
Web browsing with ARKit + SceneKit + Metal
Test with RSpec + Capybara + selenium + chromedriver
JUnit 5 parameterization test is super convenient
Output test coverage with clover + gradle
Test API often used in AssertJ
Micro benchmark made with JFR API
Build a web application with Javalin
Output JUnit test report in Maven
Web application creation with Nodejs with Docker
Copy and paste test with RSpec
Test list inclusion relationships with AssertJ