Run Golang Tests with Github Actions

Automation is great (right?!) and it can be so easy these days to run your tests automatically on any new pull request or code change. In this post we outline how you can automatically run your Go (golang) test for your project by using Github Actions. The results will then show within Github and is configured using a yaml file.

To get this running, you will need to create a workflow file (as shown below). Which will essentially do the following:

  • Download Go (using setup-go)
  • Grab project files & dependencies
  • Build the project
  • Run your tests

{project}/.github/workflows/go.yml

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
name: Go
on: [push]
jobs:

  build:
    name: Build
    runs-on: ubuntu-latest
    steps:

    - name: Download Go
      uses: actions/setup-go@v2
      with:
        go-version: 1.18
      id: go

    - name: Check out code into the Go module directory
      uses: actions/checkout@v2

    - name: Get dependencies
      run: |
        go get -v -t -d ./...        

    - name: Build
      env:
        GOPROXY: "https://proxy.golang.org"
      run: go build .

    - name: Test
      env:
        GOPROXY: "https://proxy.golang.org"
        AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
        AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
      run: go test -v .

Commit this file and push, and it will run automatically for you.

Example

github actions running go tests github actions running go tests in pull request

Secrets

Most of the above is as simple as copy and paste, but near the end we have added some example environment variables, AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY. These use Github secrets and allow you pass important/sensitive information to your application/tests.

1
MY_EXAMPLE_ENV: ${{ secrets.MY_EXAMPLE_ENV }}

For more info on setting these up, try Github’s help docs.