Movatterモバイル変換


[0]ホーム

URL:


Sitemap
Open in app

Richard Alexandrovich Bergholz

In this article, I want to show how to write a test for HTTP handlers that interact with the database using the httptest package.

We will look at how to inject the necessary dependencies and mock the database calls.

Go httptest Package

https://pkg.go.dev/net/http/httptest

Go has an amazing testing package in its standard library httptest package. It provides a small set of structures and functions for HTTP testing.

Let’s have a look at how you can use the httptest package and build better end-to-end and http tests for your Go handlers.

A Basic Handler

First, creates a directory and initialize thego.mod file:

mkdir test-handlers-gogo mod init

Here is the basic handler that returns an HTTP 200 (OK) status code and a ‘hello world!’ message. This is our handler:

and the test:

We just construct a request, a response, and pass them as a parameter to our handler function. Then check the status code and response body.

As you can see, Go’stesting andhttptest packages make testing our handlers extremely simple.

I hope you are now clear about the usage httptest package to test handlers. That’s the main idea. But more clarifying, I give an example on CRUD API.

Simple CRUD API

I created a simple CRUD API that has these endpoints:

  • Send a POST request to/v1/book to create a new book
  • Send GET request to/v1/book gets all book
  • Send DELETE request to/v1/book/:id delete book according to the given id
  • Send PUT request to/v1/book/:id update book information

I don’t show how to build the API, you can checkhere the API. We will just write a test for it.

Let’s start with mocking the database calls:

Let’s define structs for test cases:

Test Handler (POST Method)

Now, we can write a test for AddBookHandler:

  • Inject the database calls that we mocked before.
  • Define test cases.
  • And run the test cases.

Test Handler (Delete Method + Parameter)

When sending a request to the DeleteBook endpoint, we need an id parameter. Let’s look at how we can add parameters while testing:

The rest of the handler tests are available on theGitHub repository.

→ Have a Good Day ←

--

--

Serhat Karabulut
Serhat Karabulut

Written by Serhat Karabulut

Gopher - Software Developer @Trendyol

No responses yet


[8]ページ先頭

©2009-2025 Movatter.jp