-
Notifications
You must be signed in to change notification settings - Fork 0
Unit Tests
Unit tests are functions that test specific features of a project.
Testing is done in test files, which usually have the package name and _test
as the suffix, ie. foo_test.go
One reason is that they are a way to demonstrate that a feature is working as intended. The following example is very simple, but a complex feature could have many scenarios, each of which requires a test case. Another reason is the fact that we work as a team, so our code tends to depend on each other's successful implementations. Unit testing assures people using the feature you added is working as intended and is safe to use.
We create a test called TestAdd
which will test a function that returns the sum of two int
:
func TestAdd(t *testing.T) {}
Note the parameter for all unit tests is always the same: t *testing.T
.
There's different ways to structure a unit test, but a common organization technique is the principle of triple A (AAA) testing.
- Arrange - this involves initializing any test variables that will be used.
- Act - simply calling the function that is the subject of the test.
- Assert - making some sort of comparison that our actual test result matches with our expectation.
func TestAdd(t *testing.T){
// Arrange
x := 1
y := 2
expected := 3
// Act
actual := Add(x, y)
// Assert
if actual != expected {
t.Errorf("got %d, wanted %d", actual, expected)
}
}
We write as little code as possible to make the above test pass:
func Add(a int, b int) int {
return a + b
}
The above function should pass the test. Should it fail, refactor the function (not the test) until the test passes.