To write unit tests for encoding and decoding functions in Go, you can follow these steps:
Create a new test file: Create a new file with the name example_test.go
. This naming convention is important as Go's testing package recognizes files that end with _test.go
as test files.
Import the necessary packages: Import the packages required for testing. You will need the testing
package for writing tests and the package that contains your encoding and decoding functions.
package main
import (
"testing"
"your-package-name" // Import the package containing the encoding and decoding functions
)
Test
followed by a descriptive name. The test function should accept a *testing.T
parameter, which is used for reporting test failures or successes.func TestEncode(t *testing.T) {
// Write your test code here
}
t.Run()
function to separate different test cases.func TestEncode(t *testing.T) {
cases := []struct {
input string
expected string
}{
{input: "hello", expected: "encoded-hello"},
{input: "world", expected: "encoded-world"},
{input: "go", expected: "encoded-go"},
}
for _, tc := range cases {
t.Run(tc.input, func(t *testing.T) {
output := yourpackage.Encode(tc.input)
if output != tc.expected {
t.Errorf("Encode(%q) = %q, expected %q", tc.input, output, tc.expected)
}
})
}
}
TestDecode
and define the test cases.func TestDecode(t *testing.T) {
cases := []struct {
input string
expected string
}{
{input: "encoded-hello", expected: "hello"},
{input: "encoded-world", expected: "world"},
{input: "encoded-go", expected: "go"},
}
for _, tc := range cases {
t.Run(tc.input, func(t *testing.T) {
output := yourpackage.Decode(tc.input)
if output != tc.expected {
t.Errorf("Decode(%q) = %q, expected %q", tc.input, output, tc.expected)
}
})
}
}
go test
. Go will automatically discover and run the test functions.$ go test
That's it! You have written unit tests for the encoding and decoding functions in Go. Running go test
will execute the test functions and report any failures or successes.