Start learning free

LESSON 135 OF 173 · BACKEND: TESTS AND RUNNING IT

Test the Errors in Go

Practice

Tests of the happy path ask for things that exist. Bugs like to hide on the other path, the error, because nobody tries it twice by hand. The shop has no product 99, so it must answer 404 Not Found with its JSON error. A 200 would tell the app that called the shop that everything is fine.

s.Equal can compare whole maps: it passes only when both have the same keys with the same values. Here is a check of a whole product, on another route:

response, _ := http.Get(server.URL + "/products/4")
var product map[string]any
json.NewDecoder(response.Body).Decode(&product)
s.Equal(map[string]any{"id": 4, "name": "Pen", "price": 2, "category": "office"}, product)

The request your new test sends, and what the shop answers:

GET /products/99  →  404  {"error": "Product not found"}

The check runs your tests on the shop and on two broken copies: one answers 200 for a missing product, the other answers 404 with an HTML page instead of JSON. TestOneProduct passes on both. The output must be:

Your tests on the shop:
  TestMissingProduct ... ok
  TestOneProduct ... ok
  2 tests: OK
Your tests on a copy that answers 200 for a missing product:
  TestMissingProduct ... FAIL
    Not equal: expected 404, actual 200
  TestOneProduct ... ok
  2 tests: 1 failed, so they caught this bug
Your tests on a copy that answers an HTML page for a missing product:
  TestMissingProduct ... FAIL
    Not equal: expected map[error:Product not found], actual map[]
  TestOneProduct ... ok
  2 tests: 1 failed, so they caught this bug

Your task: below TestOneProduct, write TestMissingProduct: GET /products/99, check that the status code is 404, decode the body into data, and check that it equals map[string]any{"error": "Product not found"}.


Assignment
Follow the Coding Tutorial to write a test for a product that doesn't exist.


Hint
You need both checks: the status catches one broken copy, the body catches the other. When the body isn't JSON, Decode fails and data stays empty, so it prints as map[].


STEP 1 OF 6
    Ctrl + Enter to check

    Test Not Found 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