Start learning free

LESSON 134 OF 173 · BACKEND: TESTS AND RUNNING IT

Test the Answer in Go

Practice

Your first test checks only the status. A shop that answers 200 with the wrong list still passes it. To test the list itself, read the body: json.NewDecoder(response.Body).Decode(&products) turns the JSON text into Go values. For GET /products, declare products as a []map[string]any: a slice with one map per product.

Once the body is Go data, you check it with tools you already know: len, slice indexes and map keys. Here is a check on another route, product 2, the Notebook:

response, _ := http.Get(server.URL + "/products/2")
var product map[string]any
json.NewDecoder(response.Body).Decode(&product)
s.Equal("Notebook", product["name"])

The check runs your tests on the shop and on two broken copies: one leaves out the last product, the other lists the cheapest product first. Both still answer 200, so only a test of the body catches them. The output must be:

Your tests on the shop:
  TestProductsAnswer200 ... ok
  TestProductsList ... ok
  2 tests: OK
Your tests on a copy that leaves out the last product:
  TestProductsAnswer200 ... ok
  TestProductsList ... FAIL
    Not equal: expected 4, actual 3
  2 tests: 1 failed, so they caught this bug
Your tests on a copy that lists the cheapest product first:
  TestProductsAnswer200 ... ok
  TestProductsList ... FAIL
    Not equal: expected "Mug", actual "Pen"
  2 tests: 1 failed, so they caught this bug

Your task: below the first test, write TestProductsList: start a test server for app, GET /products, decode the body into products, and check that there are 4 products and that the first one's "name" is "Mug".


Assignment
Follow the Coding Tutorial to write a second test that checks the list in the answer.


Hint
Slices count from 0, so the first product is products[0], a map. A test stops at its first failed check, so each broken copy shows one message.


STEP 1 OF 6
    Ctrl + Enter to check

    Test Json Body 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