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.
assertEquals 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:
ResponseEntity<Map> response = client.getForEntity("/products/4", Map.class);
assertEquals(Map.of("id", 4, "name", "Pen", "price", 2, "category", "office"), response.getBody());
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. Reading an HTML page as a Map throws an exception, so that copy shows ERROR, which counts as a failed test. 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
AssertionError: expected: <404> but was: <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 ... ERROR
UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [interface java.util.Map] and content type [text/html;charset=utf-8]
testOneProduct ... ok
2 tests: 1 failed, so they caught this bug
Your task: below testOneProduct, write testMissingProduct: GET /products/99 reading a Map, check that the status code is 404, and check that response.getBody() equals Map.of("error", "Product not found").
Assignment
Follow the Coding Tutorial to write a test for a product that doesn't exist.
Hint
The status check catches the copy that answers 200. The HTML copy can't be read as a Map, so the request itself stops the test. The body check makes sure the 404 carries the shop's own JSON error.
Free plan: 30 tutor messages. PRO is unlimited.
