Enhancing Golang Unit Tests: From Standard Testing to Testify

Kadir Doğuş Seçkin
3 min readSep 21, 2024

--

Hello everyone. In this article, we will explore how to write unit tests in Golang. Unit testing is a critical aspect of software development, helping to ensure that individual components work as expected.

We’ll start by using Golang’s built-in testing package, then extend its functionality with Testify, a popular assertion and mocking library. By the end of this guide, you'll have a clear understanding of how to create unit tests in Go.

Writing Your First Unit Test

In Go, test files must end with _test.go, and the test functions should start with Test followed by the function name you're testing. This ensures that the go test command recognizes and runs the test functions.

You can run the tests using the go test command, which will automatically detect and execute all test functions within the package

Consider the following function, CountWords, which takes a string input and returns the number of words in the text. It trims any leading or trailing spaces and handles empty or whitespace-only strings by returning 0.

func CountWords(text string) int {
if len(strings.TrimSpace(text)) == 0 {
return 0
}
words := strings.Fields(text)
return len(words)
}

We can write tests to verify that the CountWords function works correctly for different inputs. For example, we can test a simple sentence and another with extra spaces. Here’s how we can test this function

func TestCountWords(t *testing.T) {
sentence := "Go is awesome"
actual := CountWords(sentence)
expected := 3

if actual != expected {
t.Errorf("CountWords(%q) = %d, Should be %d", sentence, actual, expected)
}
}

func TestCountWordsWithWhiteSpaces(t *testing.T) {
sentence := " Go "
actual := CountWords(sentence)
expected := 1

if actual != expected {
t.Errorf("CountWords(%q) = %d, Should be %d", sentence, actual, expected)
}
}

The TestCountWords and TestCountWordsWithWhiteSpaces functions demonstrate two different cases where we test the CountWords function. Both test functions take a *testing.T parameter, which is provided by Go's testing package. This parameter allows us to log errors and control the flow of the test execution.

  • TestCountWords: This test checks if the function correctly counts the words in a simple sentence, "Go is awesome". The expected word count is 3. If the actual result doesn't match the expected count, the t.Errorf function is called to log an error, indicating the mismatch.
  • TestCountWordsWithWhiteSpaces: This test ensures that the function handles extra white spaces correctly. The input sentence, " Go ", has leading and trailing spaces, but the function should still return 1, as there is only one word.

Enhancing Tests with Testify

Here, we’ve been using Go’s standard testing package. However, with Testify, we can make assertions in a simpler and more expressive way. It also brings additional features like mocking, which allows us to write more flexible and comprehensive tests. Let's explore how Testify can enhance our test cases.

First, we need to install the Testify package by running the following command in your terminal:

go get github.com/stretchr/testify

Now that we’ve installed the Testify package, let's take a look at how it simplifies the process of writing unit tests. Testify provides convenient assertion functions that make our tests cleaner and easier to read. Here are a few examples:

func TestCountWords(t *testing.T) {
sentence := "Go is awesome"
actual := CountWords(sentence)
expected := 3

assert.Equal(t, expected, actual, "they should be equal")
}

func TestCountWordsWithWhiteSpaces(t *testing.T) {
sentence := " Go "
actual := CountWords(sentence)
expected := 1

assert.Equal(t, expected, actual, "they should be equal")
}

Conclusion

Using Testify’s assertion functions and other nifty features, we can make our tests cleaner, easier to maintain, and more flexible. Instead of writing custom error messages and manually comparing values, Testify provides a more expressive and concise way to verify that our functions behave as expected. This approach is particularly helpful when writing multiple test cases, as it keeps the code DRY (Don't Repeat Yourself) and consistent.

By combining Go’s built-in testing package with the features offered by Testify, we can write more maintainable and readable unit tests. Testify not only simplifies assertions, but also offers additional functionality like mocking, which can make your tests more robust and flexible.

That’s all for now!

If you found this article helpful, feel free to subscribe and give it a clap for more articles.

Additional Resources:

--

--

Responses (1)