Your tests so far only read the shop. A test can also add to it: client.PostAsJsonAsync sends a POST request, and its second argument is the body, an object like new { name = "Ana" } that the client sends as JSON.
Test("add customer", async () => {
var client = app.GetTestClient();
var response = await client.PostAsJsonAsync("/customers", new { name = "Ana" });
Assert.Equal(201, (int)response.StatusCode);
});
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:
one product ... ok
add product ... ok
2 tests: OK
Your tests on a copy that answers 201 but never saves the product:
one product ... ok
add product ... FAIL
Assert.Equal() Failure: Expected "{"id":5,"name":"Plant","price":15,"category":"home"}", Actual "{"error":"Product not found"}"
2 tests: 1 failed, so they caught this bug
Your tests on a copy that gives every new product the id 1:
one product ... ok
add product ... FAIL
Assert.Equal() Failure: Expected "{"id":1,"name":"Plant","price":15,"category":"home"}", Actual "{"id":1,"name":"Mug","price":12,"category":"kitchen"}"
2 tests: 1 failed, so they caught this bug
Your task: below the "one product" test, write a test named "add product". With one client, POST a Plant (price 15, category "home") to /products, check that the status is 201, read the JSON answer into newProduct, then GET /products/ followed by its id and check that this answer's text equals newProduct.GetRawText().
Assignment
Follow the Coding Tutorial to write a test that POSTs a product and then GETs it back.
Hint
When you add the number from newProduct.GetProperty("id").GetInt32() to "/products/", C# turns it into text for you. Write the GET as response = … without var: response exists already. The last check compares newProduct.GetRawText() with the GET's text, from ReadAsStringAsync().
Free plan: 30 tutor messages. PRO is unlimited.
