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.
func TestGetItems_Success(t *testing.T) {// create a testapitest.New().// add an application to be testedHandlerFunc(FiberToHandlerFunc(newApp())).// send a GET request to get all items dataGet("/api/v1/items").// expect the response status code is equals 200Expect(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.
func TestGetItem_Success(t *testing.T) {// get the sample data for item entityvar item models.Item = getItem()// create a testapitest.New().// run the cleanup() function after the test is finishedObserve(cleanup).// add an application to be testedHandlerFunc(FiberToHandlerFunc(newApp())).// send a GET request to get item data by IDGet("/api/v1/items/" + item.ID).// expect the response status code is equals 200Expect(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).
func TestGetItem_NotFound(t *testing.T) {apitest.New().// add an application to be testedHandlerFunc(FiberToHandlerFunc(newApp())).// send GET request to get the item data by IDGet("/api/v1/items/0").// expect the response status code is equals 404Expect(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 ...