Writing a unit test
A unit test ideally tests whether a single unit (a function, a group of interrelated functions, or the methods of a type) behaves as expected.
How to do it...
- Create unit test files with the
_test.go
suffix. Forsort.go
, we createsort_test.go
. The files that end with_test.go
will be excluded from a regular build:package sort
Tip
You can also write tests in a separate test package that ends with _test
. In this example, it becomes package sort_test
. Writing tests in a separate package allows you to test the functions of a package as they are seen from the outside because you will not have access to the unexported names of the package under test. You will have to import the package under test.
- The Go testing system will run functions that follow the
Test<Feature>(*testing.T)
pattern. Declare a test function that fits this pattern, and write a unit test that exercises a behavior:func TestSortTimesAscending(t *testing.T) { &...