Search⌘ K
AI Features

Authentication Feature Testing in REST API

Explore how to test authentication features in REST API applications built with Go. This lesson guides you through setting up a testing environment, creating test cases for sign-up and login including success and failure scenarios, and using the apitest library to validate responses. By the end, you'll understand how to implement comprehensive tests for user authentication ensuring your backend is reliable and secure.

Test the application

The testing database is already prepared for testing. To create a test, we add a file called api_test.go in the project’s root directory. After creating the file, we add a function called newApp() to create an application for testing.

Go (1.18.2)
// newApp returns application
func newApp() *fiber.App {
// create a new application
var app *fiber.App = NewFiberApp()
// connect to the testing database
database.InitDatabase(utils.GetValue("DB_TEST_NAME"))
// return the application
return app
}

In the code above, the application for testing purposes is created. This function is similar to the main function inside the main.go file. The difference in this case is that the testing database is used instead of the actual application database.

Before creating the first test, we create the helper function to get the faker or sample data for the item entity. We add a helper function called getItem() after the newApp() function declaration.

Go (1.18.2)
// getItem returns sample data for item entity
func getItem() models.Item {
// connect to the test database
database.InitDatabase(utils.GetValue("DB_TEST_NAME"))
// seed the item data to the test database
// the sample data is stored in "item" variable
item, err := database.SeedItem()
if err != nil {
panic(err)
}
// return the sample data for item entity
return item
}

As seen in the code above, the getItem() function is created to get the sample data for the item entity. The sample item data is inserted into the database with the SeedItem() function. The SeedItem() function returns the sample data for the item entity that is stored inside the item variable. The item ...