Start learning free

LESSON 136 OF 173 · BACKEND: TESTS AND RUNNING IT

Test a POST

Practice

Your tests so far only read the shop. A test can also add to it: client.postForEntity sends a POST request. It takes the path, the body (a Map.of(...) that the client sends as JSON) and the type to read the answer into.

void testAddCustomer() {
    TestRestTemplate client = new TestRestTemplate();
    ResponseEntity<Map> response = client.postForEntity("/customers", Map.of("name", "Ana"), Map.class);
    assertEquals(201, response.getStatusCode().value());
}

A 201 Created only says the app answered well. It doesn't prove that the new thing was saved. To know that, the test asks for it back with a GET, using the id from the answer, and checks that it gets the same thing.

In the shop, the Plant gets the next id, 5, and asking for product 5 must give back the very same product:

POST /products  {"name": "Plant", "price": 15, "category": "home"}
  →  201  {"id": 5, "name": "Plant", "price": 15, "category": "home"}
GET /products/5  →  the same product

The check runs your tests on the shop, then on two broken copies: one answers 201 but never saves the product, the other gives every new product the id 1. Your tests must pass on the shop and catch both copies:

Your tests on the shop:
  testAddProduct ... ok
  testOneProduct ... ok
  2 tests: OK
Your tests on a copy that answers 201 but never saves the product:
  testAddProduct ... FAIL
    AssertionError: expected: <{category=home, id=5, name=Plant, price=15}> but was: <{error=Product not found}>
  testOneProduct ... ok
  2 tests: 1 failed, so they caught this bug
Your tests on a copy that gives every new product the id 1:
  testAddProduct ... FAIL
    AssertionError: expected: <{category=home, id=1, name=Plant, price=15}> but was: <{category=kitchen, id=1, name=Mug, price=12}>
  testOneProduct ... ok
  2 tests: 1 failed, so they caught this bug

Your task: below testOneProduct, write testAddProduct. With one client, POST a Plant (price 15, category "home") to /products, check that the status is 201, keep the body of the answer in newProduct, then GET /products/ followed by its id and check that this body equals newProduct.


Assignment
Follow the Coding Tutorial to write a test that POSTs a product and then GETs it back.


Hint
"/products/" + newProduct.get("id") gives "/products/5": when one side of + is a String, Java turns the other side into text. For the GET, reuse response with no type in front, as it exists already. The last check compares the whole body of the GET with newProduct, newProduct first.


STEP 1 OF 7
    Ctrl + Enter to check