How to test your Go code with Github actions

Gleb Kletskov
3 min readMay 8, 2021

Introduction

The process of testing is really important in Software development. Developers should be shure that their code is stable and meets the requirements of project. There are many types of testing software — unit testing, E2E (end-to-end), integration testing and many more. The most popular and easy way to test your code is unit testing. A unit test is a way of testing a unit — the smallest piece of code that can be logically isolated in a system. In most programming languages, that is a function, a subroutine, a method or property. We can run tests locally, on our laptops and PCs, but there is a way to do it faster and more efficient — to run tests in CI systems.
With CI systems we can run our unit tests in the cloud, saving time and computer resources. In this article we are learning how to test small web-server written in GoLang with Github Actions — one of the most popular CI systems. Github Actions is available for all repositories hosted on Github.

Init the project

Just create repository on the Github and clone it.

Init the Go Module

First of all you will need to init the Go Module. To read more about go modules you can click here.

go mod init github.com/<user>/<repo>

Create main.go file

After this — create main.go file in cmd folder (According to best practicies).

Create config.go file

Lets start with out web-server. Just create the basic folder structure and create config.go file for the basic configuration of our server.

Install gorilla/mux router

We will use gorilla/mux package for its router. This is one of the most popular http routers for golang.

go get github.com/gorilla/mux

Now we are ready to write some basic code for the our apiserver.

Write apiserver.go file

Write HandleHello.go file

This is really a simple handler for the test that our server works

Now you can update your main.go file and check that server works (just run main.go file and go to localhost:8082)

Install stretchr/testify

We will test our code with stretchr/testify package — this is one of the most popular tools for testing golang code.

go get github.com/stretchr/testify

Write apiserver_test.go file

This is first test file for our apiserver. Here we will create instance of server and send a request to it. After this we will martch the response from server to string “Hello world”.

You can check the result with this command:

go test -v ./...

Add Github actions file

Create .github folder in the root of your project and after this create .github/workflows/go.yml file.

And push it to the remote repo. After this you can go the Actions tab of your repository and see that your tests is passed 🙂

Hope that this little article was useful for you!
Written by Kletskov Gleb, frontend software engineer in Mail.ru Group.

--

--