Start learning free

LESSON 135 OF 173 · BACKEND: TESTS AND RUNNING IT

Test the Errors in C#

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.

To check the error message, read the body as JSON and take one key with GetProperty. Add GetString(): Assert.Equal finds a string equal only to another string, never to a JsonElement. Here is a check of one product's category, on another route:

var response = await client.GetAsync("/products/4");
var product = await response.Content.ReadFromJsonAsync<JsonElement>();
Assert.Equal("office", product.GetProperty("category").GetString());

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. The test "one product" passes on both. Reading an HTML page as JSON throws a JsonException, so the test stops with ERROR, which counts as failed too. The output must be:

Your tests on the shop:
  one product ... ok
  missing product ... ok
  2 tests: OK
Your tests on a copy that answers 200 for a missing product:
  one product ... ok
  missing product ... FAIL
    Assert.Equal() Failure: Expected 404, Actual 200
  2 tests: 1 failed, so they caught this bug
Your tests on a copy that answers an HTML page for a missing product:
  one product ... ok
  missing product ... ERROR
    JsonException: '<' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.
  2 tests: 1 failed, so they caught this bug

Your task: below "one product", write the test "missing product": GET /products/99, check that the status code is 404, read the body into body, and check that its "error" is "Product not found".


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


Hint
The status check catches one broken copy; reading the body catches the other, because an HTML page isn't JSON. Don't forget GetString() before you compare with a string.


STEP 1 OF 6
    Ctrl + Enter to check

    Test Not Found in C#

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