...

/

CRUD Feature Testing in REST API

CRUD Feature Testing in REST API

Learn how to test the CRUD feature in the REST API Application.

Test the CRUD feature

Test CRUD features, including creating, retrieving, updating, and deleting an item.

Test for getting all items feature

To get started, we create the only test case that can be created for the get all items feature.

Press + to interact
func TestGetItems_Success(t *testing.T) {
// create a test
apitest.New().
// add an application to be tested
HandlerFunc(FiberToHandlerFunc(newApp())).
// send a GET request to get all items data
Get("/api/v1/items").
// expect the response status code is equals 200
Expect(t).
Status(http.StatusOK).
End()
}

In the code above, the test case for the get all items feature is created. The expected result of this test is the response status code 200.

Test for getting item by ID feature

We create the following two test cases for the get item by ID feature. Getting the item is successful. Getting the item fails(the item is not found).

First, we create the test case for the get item by ID feature.

Press + to interact
func TestGetItem_Success(t *testing.T) {
// get the sample data for item entity
var item models.Item = getItem()
// create a test
apitest.New().
// run the cleanup() function after the test is finished
Observe(cleanup).
// add an application to be tested
HandlerFunc(FiberToHandlerFunc(newApp())).
// send a GET request to get item data by ID
Get("/api/v1/items/" + item.ID).
// expect the response status code is equals 200
Expect(t).
Status(http.StatusOK).
End()
}

As seen in the code above, the test case for getting an item is created. The expected result of this test case is the response status code 200.

Next, we create the test case for failing to get an item by ID (the item is not found).

Press + to interact
func TestGetItem_NotFound(t *testing.T) {
apitest.New().
// add an application to be tested
HandlerFunc(FiberToHandlerFunc(newApp())).
// send GET request to get the item data by ID
Get("/api/v1/items/0").
// expect the response status code is equals 404
Expect(t).
Status(http.StatusNotFound).
End()
}

In the code above, the test case for failing to get an item by ID is created. The expected result is the response status code 404 because the item data ...