Start learning free

LESSON 134 OF 173 · BACKEND: TESTS AND RUNNING IT

Test the Answer

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: response.Content.ReadFromJsonAsync<JsonElement>() turns the JSON text into a JsonElement. For GET /products that is an array with one object per product.

A JsonElement has methods to read it: GetArrayLength() counts an array's items, [0] gives the first item, GetProperty("price") reads one key, and GetString() or GetInt32() turn a value into a C# string or int. Here is a check on another route, product 2, the Notebook:

var response = await client.GetAsync("/products/2");
var product = await response.Content.ReadFromJsonAsync<JsonElement>();
Assert.Equal(7, product.GetProperty("price").GetInt32());

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:
  products answer 200 ... ok
  products list ... ok
  2 tests: OK
Your tests on a copy that leaves out the last product:
  products answer 200 ... ok
  products list ... FAIL
    Assert.Equal() Failure: Expected 4, Actual 3
  2 tests: 1 failed, so they caught this bug
Your tests on a copy that lists the cheapest product first:
  products answer 200 ... ok
  products list ... FAIL
    Assert.Equal() Failure: Expected "Mug", Actual "Pen"
  2 tests: 1 failed, so they caught this bug

Your task: below the first test, write the test "products list": GET /products, read 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
Arrays count from 0, so the first product is products[0], a JSON object. A failed Assert.Equal ends its test at once, so each broken copy shows one message.


STEP 1 OF 6
    Ctrl + Enter to check