Start learning free

LESSON 137 OF 173 · BACKEND: TESTS AND RUNNING IT

Fresh Data for Every Test in Go

Practice

Tests must not depend on each other. If all your tests use the same app, they share one shop: a Plant added by one test is still there when the next test runs. Then a test can pass or fail just because of which test ran before it.

The test runner has a fix: a method named SetupTest on your test type. The runner calls it before each test, every time, on the same s the test gets, so it's the place to build fresh data. What SetupTest stores in a field of s, the test that runs next can use.

type CartTests struct {
	Suite
	cart []string
}

func (s *CartTests) SetupTest() {
	s.cart = []string{}
}

func (s *CartTests) TestAdd() {
	s.cart = append(s.cart, "Mug")
	s.Equal(1, len(s.cart))
}

func (s *CartTests) TestEmpty() {
	s.Equal(0, len(s.cart))
}

TestAdd runs first and puts a Mug in the cart, yet TestEmpty still finds an empty cart: SetupTest made a new one before it. In the shop, newApp() does that job: each call builds a new shop with its own four products. With a new shop and its own test server in every test, your two tests get these answers in any order:

TestAddProduct:     POST /products  (a Plant)  →  {"id": 5, …}
TestCountProducts:  GET /products  →  a list of 4 products

The check runs your tests, then again in the opposite order, then once more with every test on the same shop, to show what fresh data saves you from. It must print:

Your tests on the shop:
  TestAddProduct ... ok
  TestCountProducts ... ok
  2 tests: OK
Your tests again, in the opposite order:
  TestCountProducts ... ok
  TestAddProduct ... ok
  2 tests: OK
Your tests if every test got the same shop:
  TestAddProduct ... ok
  TestCountProducts ... FAIL
    Not equal: expected 4, actual 5
  2 tests: 1 failed

Your task: above TestAddProduct, write SetupTest: build a new shop with newApp(), keep it in app, and start a test server for it in s.server. Then, below TestAddProduct, write TestCountProducts: GET /products on s.server, decode the list into products, and check that it has 4 products.


Assignment
Follow the Coding Tutorial to give every test a fresh shop in SetupTest, then test that the shop still has 4 products.


Hint
The name is SetupTest, a method on *ProductTests that, like the tests, takes no parameters. s.server is a field, so store the server with =, not :=. A list of products decodes into a []map[string]any, and len(...) counts its items.


STEP 1 OF 7
    Ctrl + Enter to check

    Test Fresh Data in Go

    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free