introduction to testing in go

i

Testing is hugely important in all software. Being able to ensure the correctness of your code and ensure that any changes you make don’t end up breaking anything else in different parts of your codebase is hugely important.

Well, of course by testing, you can surely use your print() statement and maybe use a debugger.

But in this article, we’re going to be using the standard "testing" package.

First this is my project structure:

Always append _test to your testing go files name

Now lets build a simple program

package main

//Increment will increment :)
func Increment(x int) int {
	return x + 1
}

func main() {

}

Nothing fancy here. It just returns x+1 for a given x.

Now lets actually check if thats the case.

In the main_test.go file.

  • import testing
  • create a function that will test your function
  • t.Error() if your condition fails
package main

import (
	"testing"
)

func TestIncrement(t *testing.T) {
	if Increment(3) != 4 {
		t.Error("Expected 3+1 to equal 4")
	}
}

see. Now lets run it. In my vscode as I use go extension, I can just click on run test.

You can also just run go test

You can also pass -v, for more verbose

for checking coverage you can pass -cover

testify

As you can see passing these arguments gives us more information, we can actually be a bit fancier and can use testify

go get github.com/stretchr/testify

Now we can change this

if Increment(3) != 4 {
		t.Error("Expected 3+1 to equal 4")
	}

to

	assert.Equal(t, Increment(2), 3)

Table Driven Testing

So far I used like

if Increment(3) != 4 {
		t.Error("Expected 3+1 to equal 4")
	}

But what if I want to try different test cases.

Just store those test cases in a array and use a loop to iterate and then test it.

var tests = []struct {
			input    int
			expected int
	}{
			{1, 2},
			{4, 5},
			{9, 10},
			{99999, 100000},
	}

After creating this array. Now we can just iterate through it

for _, test := range tests {
  if Increment(test.input) != test.expected {
    t.Error("Test Failed: {} inputted, {} expected, recieved: {}", test.input, test.expected, Increment(test.input))
	}
}

Here’s the full code:

package main

import (
	"testing"
	"github.com/stretchr/testify/assert"
)

func TestIncrement(t *testing.T) {
		assert.Equal(t, Increment(2), 3)
}

func TestTableIncrement(t *testing.T) {
	var tests = []struct {
			input    int
			expected int
	}{
			{1, 2},
			{4, 5},
			{9, 10},
			{99999, 100000},
	}

	for _, test := range tests {
			if Increment(test.input) != test.expected {
					t.Error("Test Failed: {} inputted, {} expected, recieved: {}", test.input, test.expected, Increment(test.input))
			}
	}
}

Now lets run it.

At first, this might not look like a big deal. But once your code grew larger and getting new and newer features, this testing can be really useful.

Happy coding

About the author

vigneshwar

Add comment

Leave a Reply

By vigneshwar

Most common tags

%d bloggers like this: