Skip to content

Unit Tests

kstola2 edited this page Sep 9, 2019 · 2 revisions

What are they?

Unit tests are functions that test specific features of a project.

Where do they go?

Testing is done in test files, which usually have the package name and _test as the suffix, ie. foo_test.go

Why are they important?

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.

Example

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.

Clone this wiki locally