Start learning free

LESSON 139 OF 173 · BACKEND: TESTS AND RUNNING IT

Test the Login in C#

Practice

A route behind a login has two jobs: keep out anyone without a valid token, and let in someone who logged in. A bug can break either job, so a good test suite checks both sides.

The token is random, a new one at every login, so a test can't type it in. It does what a real client does: it logs in, reads the token from the answer, and sends it back in the Authorization header, written as Bearer, a space, then the token. An HttpClient sends the headers in its DefaultRequestHeaders with every request, like in this call to another route:

client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
var response = await client.GetAsync("/orders");

Here, the test me without token already checks that GET /me answers 401 when there's no token. The check runs your tests on the shop and on two broken copies: one whose /me forgets to cut "Bearer " off the header, so it keeps everyone out, and one that lets everyone in. When you're done, Run prints:

Your tests on the shop:
  me without token ... ok
  me after login ... ok
  2 tests: OK
Your tests on a copy whose /me forgets to cut "Bearer " off the header:
  me without token ... ok
  me after login ... FAIL
    Assert.Equal() Failure: Expected "{"id":1,"email":"ana@example.com"}", Actual "{"error":"Login required"}"
  2 tests: 1 failed, so they caught this bug
Your tests on a copy whose /me lets everyone in, even without a token:
  me without token ... FAIL
    Assert.Equal() Failure: Expected 401, Actual 200
  me after login ... ok
  2 tests: 1 failed, so they caught this bug

Your task: below me without token, write the test "me after login". Log Ana in with POST /login (email ana@example.com, password secret123), keep her token, call GET /me with it, and check that the answer's text is {"id":1,"email":"ana@example.com"}.


Assignment
Follow the Coding Tutorial to write a test that logs in, keeps the token and calls /me with it.


Hint
Read the login answer with ReadFromJsonAsync<JsonElement>(); the token is login.GetProperty("token").GetString(). The header's value is the text "Bearer ", with its space, plus the token.


STEP 1 OF 7
    Ctrl + Enter to check

    Test Auth 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