Learn Fiber Β· 13/14

Testing Fiber Applications

8 min read

Testing Fiber Applications πŸ§ͺ

Welcome to the thrilling world of testing your Fiber applications! "Why test?" you might ask. Well, imagine building a magnificent skyscraper without ever checking if the foundation is solid. Sooner or later, things might get a bit... wobbly. Testing is our way of ensuring our application is robust, reliable, and ready for the real world. It's the secret sauce to sleeping soundly at night, knowing your app won't crumble under pressure.

In this guide, we'll walk through the essentials of testing Fiber applications, from the basics of HTTP testing in Go to the nitty-gritty of mocking dependencies and asserting responses. Let's get our hands dirty and build some confidence in our code!


1. Introduction to HTTP Testing in Go 🚦

The Problem: Before we dive into Fiber-specific testing, let's understand the landscape. When you build a web application, you're essentially creating a series of endpoints that respond to HTTP requests. How do you verify that a GET request to /users actually returns a list of users without manually opening your browser or a tool like Postman every single time you make a change? This manual process is slow, error-prone, and frankly, a bit of a bore.

The Solution: Go comes with a fantastic built-in package called net/http/httptest. This package is our best friend for simulating HTTP requests and recording their responses. It allows us to programmatically "pretend" to be a user sending a request to our application and then inspect the response it sends back. This way, we can automate the testing of our endpoints.

Under the hood, httptest creates a mock http.ResponseWriter (to capture the response) and a mock http.Request. We can then pass these to our HTTP handler and check if the response is what we expect.

Here's a simple example of how you might test a standard Go HTTP handler:

go
package main

import (
    "net/http"
    "net/http/httptest"
    "testing"
)

func HelloWorld(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Hello, World!"))
}

func TestHelloWorld(t *testing.T) {
    // Create a new HTTP request.
    req := httptest.NewRequest("GET", "http://example.com/foo", nil)

    // Create a ResponseRecorder to record the response.
    rr := httptest.NewRecorder()

    // Call our handler with the request and response recorder.
    HelloWorld(rr, req)

    // Check the status code is what we expect.
    if status := rr.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }

    // Check the response body is what we expect.
    expected := "Hello, World!"
    if rr.Body.String() != expected {
        t.Errorf("handler returned unexpected body: got %v want %v",
            rr.Body.String(), expected)
    }
}

This is the fundamental principle of HTTP testing in Go. We create a request, capture the response, and then make assertions about the response.


2. Testing Fiber Routes using app.Test() πŸš€

The Problem: While the standard net/http/httptest package is great, Fiber provides an even more convenient way to test its routes. Setting up all the httptest boilerplate for every single route can be a bit repetitive. We want something that feels more integrated with the Fiber framework.

The Solution: The Fiber framework provides a handy app.Test() method. This function makes testing your Fiber handlers incredibly straightforward. It abstracts away the httptest setup and lets you focus on the request and the assertions.

Let's imagine you have a simple Fiber application:

go
// app.go
package main

import "github.com/gofiber/fiber/v2"

func setupApp() *fiber.App {
    app := fiber.New()

    app.Get("/", func(c *fiber.Ctx) error {
        return c.SendString("Hello, World!")
    })

    return app
}

func main() {
    app := setupApp()
    app.Listen(":3000")
}

Now, let's write a test for our / route using app.Test():

go
// app_test.go
package main

import (
    "net/http"
    "testing"
    "io/ioutil"
    "github.com/stretchr/testify/assert"
)

func TestHelloWorldRoute(t *testing.T) {
    // Arrange
    app := setupApp()
    req, _ := http.NewRequest("GET", "/", nil)

    // Act
    resp, err := app.Test(req)

    // Assert
    assert.NoError(t, err)
    assert.Equal(t, http.StatusOK, resp.StatusCode)

    body, err := ioutil.ReadAll(resp.Body)
    assert.NoError(t, err)
    assert.Equal(t, "Hello, World!", string(body))
}

In this example, app.Test(req) executes the request against our Fiber app and returns an *http.Response. We can then inspect this response to our heart's content. Notice how much cleaner this is? We didn't have to create a httptest.ResponseRecorder.

Interesting Fact: The app.Test() method is essentially a wrapper around net/http/httptest, so you're still using the power of the standard library, but with a much nicer API.


3. Mocking Dependencies for Unit Tests 🎭

The Problem: Real-world applications are rarely self-contained. Your handlers often depend on other components, like a database, a third-party API, or some other service. When you're writing a unit test for a handler, you want to test the handler's logic in isolation, not the entire chain of dependencies. If your test fails, you want to know it's because of the handler, not because your database was down or the external API changed.

The Solution: This is where mocking comes in. Mocking is the practice of creating "fake" versions of these dependencies that you can control in your tests. These fake objects behave like the real ones but return predefined data, allowing you to test your handler's logic without any external factors.

Let's consider a handler that fetches a user from a database.

First, we define an interface for our user repository:

go
// user.go
package main

type User struct {
    ID   int
    Name string
}

type UserRepository interface {
    GetUser(id int) (*User, error)
}

Our handler will depend on this interface:

go
// handler.go
package main

import (
    "github.com/gofiber/fiber/v2"
    "strconv"
)

func GetUserHandler(repo UserRepository) fiber.Handler {
    return func(c *fiber.Ctx) error {
        id, err := strconv.Atoi(c.Params("id"))
        if err != nil {
            return c.Status(fiber.StatusBadRequest).SendString("Invalid ID")
        }

        user, err := repo.GetUser(id)
        if err != nil {
            return c.Status(fiber.StatusNotFound).SendString("User not found")
        }

        return c.JSON(user)
    }
}

Now, for our test, we'll create a mock UserRepository:

go
// handler_test.go
package main

import (
    "errors"
    "net/http"
    "testing"
    "github.com/gofiber/fiber/v2"
    "github.com/stretchr/testify/assert"
    "io/ioutil"
)

// MockUserRepository is our fake user repository.
type MockUserRepository struct {
    GetUserFunc func(id int) (*User, error)
}

func (m *MockUserRepository) GetUser(id int) (*User, error) {
    return m.GetUserFunc(id)
}

func TestGetUserHandler_Success(t *testing.T) {
    // Arrange
    mockRepo := &MockUserRepository{
        GetUserFunc: func(id int) (*User, error) {
            return &User{ID: 1, Name: "John Doe"}, nil
        },
    }

    app := fiber.New()
    app.Get("/users/:id", GetUserHandler(mockRepo))

    req, _ := http.NewRequest("GET", "/users/1", nil)

    // Act
    resp, err := app.Test(req)

    // Assert
    assert.NoError(t, err)
    assert.Equal(t, http.StatusOK, resp.StatusCode)
    
    body, _ := ioutil.ReadAll(resp.Body)
    assert.JSONEq(t, `{"ID":1,"Name":"John Doe"}`, string(body))
}

func TestGetUserHandler_NotFound(t *testing.T) {
    // Arrange
    mockRepo := &MockUserRepository{
        GetUserFunc: func(id int) (*User, error) {
            return nil, errors.New("not found")
        },
    }

    app := fiber.New()
    app.Get("/users/:id", GetUserHandler(mockRepo))

    req, _ := http.NewRequest("GET", "/users/1", nil)

    // Act
    resp, err := app.Test(req)

    // Assert
    assert.NoError(t, err)
    assert.Equal(t, http.StatusNotFound, resp.StatusCode)
}

By using an interface and a mock implementation, we can test both the success and failure cases of our handler without ever touching a real database. This makes our tests faster, more reliable, and easier to write.


4. Asserting JSON Responses and Status Codes βœ…

The Problem: You've sent a request to your handler in a test, and you've received a response. Now what? You need to verify that the response is exactly what you expect. This means checking the HTTP status code and, if you're building an API, the JSON body of the response.

The Solution: There are several ways to do this, but one of the most popular and developer-friendly is to use an assertion library. A great choice in the Go ecosystem is testify/assert. This library provides a rich set of assertion functions that make your tests more readable and concise.

Let's expand on our previous app.Test() example to see how we can use testify/assert to check the status code and JSON response.

Imagine a handler that creates a user:

go
// user_handler.go
package main

import "github.com/gofiber/fiber/v2"

type CreateUserRequest struct {
    Name string `json:"name"`
}

func CreateUserHandler(c *fiber.Ctx) error {
    req := new(CreateUserRequest)
    if err := c.BodyParser(req); err != nil {
        return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{
            "error": "Invalid request body",
        })
    }
    
    // In a real app, you would save the user to a database.
    // For this example, we'll just return the created user.
    user := &User{
        ID:   1, // A new ID would be generated
        Name: req.Name,
    }

    return c.Status(fiber.StatusCreated).JSON(user)
}

Now, let's test this handler:

go
// user_handler_test.go
package main

import (
    "net/http"
    "strings"
    "testing"
    "github.com/gofiber/fiber/v2"
    "github.com/stretchr/testify/assert"
    "io/ioutil"
)

func TestCreateUserHandler(t *testing.T) {
    // Arrange
    app := fiber.New()
    app.Post("/users", CreateUserHandler)
    
    userJSON := `{"name":"Jane Doe"}`
    req, _ := http.NewRequest("POST", "/users", strings.NewReader(userJSON))
    req.Header.Set("Content-Type", "application/json")

    // Act
    resp, err := app.Test(req)

    // Assert
    assert.NoError(t, err)
    assert.Equal(t, http.StatusCreated, resp.StatusCode, "Expected status code 201")
    
    body, err := ioutil.ReadAll(resp.Body)
    assert.NoError(t, err)
    
    expectedJSON := `{"ID":1,"Name":"Jane Doe"}`
    assert.JSONEq(t, expectedJSON, string(body), "The response body should match")
}

Here's what's happening in the // Assert section:

  • assert.NoError(t, err): This ensures that our app.Test() call didn't produce an error.
  • assert.Equal(t, http.StatusCreated, resp.StatusCode, ...): This checks if the HTTP status code is 201 Created. The last argument is an optional message that will be displayed if the assertion fails, which is great for debugging!
  • assert.JSONEq(t, expectedJSON, string(body), ...): This is a powerful assertion from testify. It compares two JSON strings and tells you if they are equivalent, ignoring whitespace and the order of keys in objects. This is much more reliable than a simple string comparison.

Using an assertion library like testify makes your tests cleaner and your intentions clearer.

Happy testing! πŸ§‘β€πŸ’»


πŸ“š Further Reading and References

Challenge

You are tasked with writing a complete unit test for a Go Fiber application handler, GetUserByID. This handler depends on a UserRepository interface to fetch user data from a persistence layer.

Your goal is to write the test suite in the main_test.go file provided in the initial code. The test must isolate the handler's logic by mocking the UserRepository dependency. You need to cover both the success case (a user is found) and the failure case (a user is not found).

Requirements:

  1. Define a MockUserRepository struct that implements the UserRepository interface. This mock should allow you to control the return values of the FindByID method for testing purposes.
  2. Write a test function named TestGetUserByID.
  3. Inside TestGetUserByID, create two sub-tests using t.Run(): one named "Success - User Found" and another named "Failure - User Not Found".
  4. For the "Success - User Found" sub-test:
    • Configure your mock to return a predefined User struct when its FindByID method is called.
    • Set up the Fiber application, injecting your mock repository.
    • Use the app.Test() method to simulate an HTTP GET request to /users/1.
    • Using the testify/assert package, assert that the HTTP response status code is http.StatusOK.
    • Assert that the JSON response body is an exact match for the expected user data (e.g., {"id":1,"name":"John Doe"}).
  5. For the "Failure - User Not Found" sub-test:
    • Configure your mock to return nil and an error when its FindByID method is called.
    • Set up the Fiber application, injecting your mock repository.
    • Use app.Test() to simulate an HTTP GET request to /users/99.
    • Assert that the HTTP response status code is http.StatusNotFound.
    • Assert that the JSON response body matches the expected error message (e.g., {"error":"User not found"}).

Expected result

The completed main_test.go file should contain a full implementation of the test suite. The final code should demonstrate a clear understanding of dependency mocking and integration testing for a Fiber handler.

It should include:

  1. A MockUserRepository struct: This struct will hold fields to control the mock's behavior, such as UserToReturn *User and ErrorToReturn error.
  2. A FindByID method for the mock: This method will be attached to the MockUserRepository and will simply return the values stored in the struct's fields, thus satisfying the UserRepository interface.
  3. A TestGetUserByID function containing two sub-tests:
    • The success sub-test will instantiate the MockUserRepository, configure it to return a valid User object, initialize the Fiber app with this mock, create a GET request using http.NewRequest, execute it with app.Test(), and finally use assert.Equal for the status code and assert.JSONEq to compare the response body with the expected JSON string.
    • The failure sub-test will follow a similar pattern, but will configure the mock to return an error, and will assert a 404 Not Found status and the corresponding error JSON in the response body.
go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.