DEV Community

Dênis Mendes
Dênis Mendes

Posted on

2

How to test API with Golang.

Hi there!

I needed to test a few requests I do in my API and then I will show to you how I did that.

First things first, you need to create an application and a file with routes:

main.go

package main

import (
    "net/http"

    "devto.com/v1/src/router"
)

func main() {
    /// Start server with Routes
    http.ListenAndServe(":3333", router.Routes())
}
Enter fullscreen mode Exit fullscreen mode

router\router.go

package router

import (
    "net/http"

    "github.com/go-chi/chi"
    "github.com/go-chi/chi/middleware"
)


func Routes() *chi.Mux {
    r := chi.NewRouter()
    r.Use(middleware.Logger)
    r.Use(middleware.Recoverer)

    r.Get("/info", func(w http.ResponseWriter, r *http.Request) {
                w.WriteHeader(http.StatusOK)
        w.Write([]byte(":)"))
    })

    return r
}
Enter fullscreen mode Exit fullscreen mode

Then we're gonna make our test for that request called info.

tests\integration\info_test.go

package integration

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

    "devto.com/v1/src/router"
)

func TestInfoRequest(t *testing.T) {
    // Set up a new request.
    req, err := http.NewRequest("GET", "/info", nil)
    if err != nil {
        t.Fatal(err)
    }

    newRecorder := httptest.NewRecorder()

    router.Routes().ServeHTTP(newRecorder, req)

    statusCode := 200
    if newRecorder.Result().StatusCode != statusCode {
        t.Errorf("TestInfoRequest() test returned an unexpected result: got %v want %v", newRecorder.Result().StatusCode, statusCode)
    }
}
Enter fullscreen mode Exit fullscreen mode

That's all! I hope it helps you to get your integration tests working.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay