Creating Unit Tests
Simple Unit Test
The following is how you could start a very simple unit test:
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSomeFunction(t *testing.T) {
tester := assert.New(t)
tester.Nil(nil)
}
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSomeFunction(t *testing.T) {
tester := assert.New(t)
tester.Nil(nil)
}
Test Cases
The following can serve as an example for unit tests with a list of cases:
package main
import (
"math"
"testing"
"github.com/stretchr/testify/assert"
)
func IsSquare(x int) bool {
y := int(math.Sqrt(float64(x)))
return x == y*y
}
func TestAListOfCases(t *testing.T) {
tester := assert.New(t)
type myCase struct {
value int
expected bool
}
for _, tc := range []myCase{
{
-4, false,
},
{
4, true,
},
{
64, true,
},
{
63, false,
},
} {
if tc.expected != IsSquare(tc.value) {
tester.Fail("IsSquare(%d) did not get %t", tc.value, tc.expected)
}
}
}
import (
"math"
"testing"
"github.com/stretchr/testify/assert"
)
func IsSquare(x int) bool {
y := int(math.Sqrt(float64(x)))
return x == y*y
}
func TestAListOfCases(t *testing.T) {
tester := assert.New(t)
type myCase struct {
value int
expected bool
}
for _, tc := range []myCase{
{
-4, false,
},
{
4, true,
},
{
64, true,
},
{
63, false,
},
} {
if tc.expected != IsSquare(tc.value) {
tester.Fail("IsSquare(%d) did not get %t", tc.value, tc.expected)
}
}
}