In this lesson, we’ll explore how to write unit tests in Go while observing best practices for testing. Go’s built-in test runner and framework seamlessly integrate with standard language tooling, allowing you to execute tests simply by running:Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
_test.go.
Below, you’ll learn how to test a function that determines whether an integer is even.
Creating the Function to Test
Begin by creating a function calledcheckEven in your main package. This function accepts an integer argument and returns "YES" if the number is even; otherwise, it returns "NO".
Writing Unit Tests in the Same Package
To test thecheckEven function, create a file named process_test.go in the same directory. In Go, test functions must start with a capital letter Test. The following example shows how to write a test case for checkEven:
checkEven returns the correct output.
To see a failing test in action, you can intentionally set the expected string to
"YESs":T. If you name a test function with a lowercase t (e.g., func testCheckEven(t *testing.T) { ... }), the test runner will not recognize it:
Testing Exported Functions from a Separate Package
Another effective strategy is testing functions from an external package. You may move your code into its own package (for example,process) and then write tests that import this package.
Imagine moving your process.go file into a subdirectory named process, and updating the package name accordingly:
process_test.go) with the following code:
Organizing Tests in a Separate Directory
Alternatively, you can maintain a dedicated directory (such astests) for your test code. This method is suitable when testing exported functions. After moving your test file into the tests directory, your test might look like this:
tests directory with:
Best Practices for Testing in Go
- Use separate test files with the
_test.gosuffix. - Always name test functions starting with a capital
Test. - For internal functions, write tests in the same package; for exported functions, consider using a separate test package.
- Keep your test code modular and reflective of actual consumer usage.
- Consolidate similar code examples to maintain clarity and conciseness in documentation.