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. getForEntity sends no headers, so you put them in an HttpHeaders and send them with exchange, like in this call to another route:
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + token);
ResponseEntity<Map> response = client.exchange("/orders", HttpMethod.GET, new HttpEntity<>(headers), Map.class);
Here, testMeWithoutToken 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:
testMeAfterLogin ... ok
testMeWithoutToken ... ok
2 tests: OK
Your tests on a copy whose /me forgets to cut "Bearer " off the header:
testMeAfterLogin ... FAIL
AssertionError: expected: <{email=ana@example.com, id=1}> but was: <{error=Login required}>
testMeWithoutToken ... ok
2 tests: 1 failed, so they caught this bug
Your tests on a copy whose /me lets everyone in, even without a token:
testMeAfterLogin ... ok
testMeWithoutToken ... FAIL
AssertionError: expected: <401> but was: <200>
2 tests: 1 failed, so they caught this bug
Your task: below testMeWithoutToken, write testMeAfterLogin. Log Ana in with POST /login (email ana@example.com, password secret123), keep her token, call GET /me with it, and check that the body equals Map.of("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
The token is (String) response.getBody().get("token"). The header's value is the text "Bearer ", with its space, plus the token.
Free plan: 30 tutor messages. PRO is unlimited.
