GitHub Actions – Run Unit Tests in Go

A typical build pipeline will see Developers check code into a repository, and then this will trigger an automated build in a system such as Jenkins, which will then check out the code, build it and run the unit tests. With GitHub actions we can shorten the feedback loop and run the tests directly on check in. We can also run the tests on a pull request. This is a really powerful addition to our build process, when working on a branch, we now know that all tests pass before the code is checked into the main branch, reducing the chance of a broken build. It may well still be desirable run unit tests in a pipeline, as this can be part of a more in-depth process with stages to run integration tests, static code analysis etc. I see no harm in duplicating the running of unit tests at the repository stage to get the benefit of quicker feedback and less chance of breaking the main branch.

GitHub Action – Run Unit Tests

Adding an action is as easy as creating a yaml file in .github/workflows directory

name: Go package

on: [push, pull_request]

jobs:
  build:

    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Set up Go
        uses: actions/setup-go@v4
        with:
          go-version: '1.18'

      - name: Build
        run: go build -v ./...

      - name: Test
        run: go test -v ./...

Specify when this will run in the on: section. Here the tests will run on push and on a pull request to the main branch.