DEV Community

loading...
Cover image for Unit testing in Go

Unit testing in Go

Karan Pratap Singh
Software Engineer & Solutions Architect
・2 min read

In this article let's discuss how we can write simple unit tests in go.

All the code from this article is available on github

I've also made a video, if you like to follow along!

Writing our first unit test

Initialize a sample module

go mod init sample
Enter fullscreen mode Exit fullscreen mode

Let's start with adding a length.go file with a Length function. This function simply returns the length of the input string.

Alt Text

In go, tests file are usually named with _test (just like we do .test.js for jest). Let's create length_test.go.

This is a very basic test function in which we'll be testing out our Length function

Alt Text

Let's add some test logic

Alt Text

Let's run it!

go test
Enter fullscreen mode Exit fullscreen mode

Yay! our test passed!

PASS
ok      sample  0.429s
Enter fullscreen mode Exit fullscreen mode

Now let's change our expected variable to 5, and re-run our test and we should see the test fail

--- FAIL: Test (0.00s)
    length_test.go:10: Expected 5 Got 4
FAIL
exit status 1
FAIL    sample  0.334s
Enter fullscreen mode Exit fullscreen mode

Multiple test cases

Let's add out test cases with input and expected outputs

This approach is similar to test.each from jest

Alt Text

Update Test_Length function to use testCases
Alt Text

Run the test cases!

PASS
ok      sample  0.347s
Enter fullscreen mode Exit fullscreen mode

Great! Thank you all for reading this article, if you have any questions don't hesitate to reach to me on twitter

Discussion (0)