Recently I have been learning Golang and of all the plethora of features this language offers one specifically caught my eye.
Golang has a package testing
which provides support for automated testing of Go packages.
So we will go through a simple problem of reversing a string in-place and write a unit test to test the reverseString function.
The solution to reverse a string is simple enough.
reverse_string.go
package devto
func reverseString(list []string) []string {
start := 0
end := len(list) - 1
for start < end {
// swap the values at indices
common.Swap(list, start, end)
start++
end--
}
return list
}
For testing purpose, we will first import the testing package.
import "testing"
Testing functions in go looks like TestXxx
So let's define a function for our reverseString function.
func TestReverseString(t *testing.T) {
}
Next, we will be defining an anonymous array of structs which contains the input & expected values (string array).
tests := []struct {
in []string
expected []string
}{
{[]string{}, []string{}},
{[]string{"a"}, []string{"a"}},
{[]string{"a", "b"}, []string{"b", "a"}},
{[]string{"a", "b", "c"}, []string{"c", "b", "a"}},
{[]string{"a", "b", "c", "d"}, []string{"d", "c", "b", "a"}},
}
We have initialized the struct with input & expected values,
to test all of these values and checking if the result is what we expected we do something like
import "reflect"
...
for _, tt := range tests {
result := reverseString(tt.in)
if !reflect.DeepEqual(result, expected) {
t.Errorf("should be %v instead of %v", expected, result)
}
}
we have imported the reflect package to check if the result that we got from the reverseString function is deepEqual to the expected value
so the final test file looks like
reverse_string_test.go
package devto
import (
"testing"
"reflect"
)
func TestReverseString(t *testing.T) {
tests := []struct {
in []string
expected []string
}{
{[]string{}, []string{}},
{[]string{"a"}, []string{"a"}},
{[]string{"a", "b"}, []string{"b", "a"}},
{[]string{"a", "b", "c"}, []string{"c", "b", "a"}},
{[]string{"a", "b", "c", "d"}, []string{"d", "c", "b", "a"}},
}
for _, tt := range tests {
result := reverseString(tt.in)
if !reflect.DeepEqual(result, expected) {
t.Errorf("should be %v instead of %v", expected, result)
}
}
}
all the test file names are of format xxx_test.go
Now to run our test file we use the command
go test devto/reverse_string_test.go
& the output would be
Running tool: /usr/local/bin/go test -timeout 30s -run ^TestReverseString$
PASS
ok ***/devto 0.005s
Oldest comments (0)