Start learning free

LESSON 146 OF 173 · BACKEND: TESTS AND RUNNING IT

Project: Test the Checkout in C#

Practice

A test suite is a set of tests that run together, one for each thing that must keep working. The shop's checkout takes real money, so it deserves one. It is loaded for you, hidden, and app.GetTestClient() gives an HttpClient that talks to it: POST /checkout takes a cart like {"items": [{"product_id": 1, "quantity": 2}]}, adds up the prices from the database, charges the card through the payment provider and answers 201 with {"status":"paid","total":24}.

A good suite tests the normal case and the edge cases, where bugs like to hide. Each test sends one request and checks the status code and the whole answer. ASP.NET Core writes JSON with no spaces, so a test can compare the answer's text with one string. Here is one test of that shape, for a shop's product page:

Test("missing product", async () => {
    var response = await client.GetAsync("/products/99");
    Assert.Equal(404, (int)response.StatusCode);
    Assert.Equal("{\"error\":\"Product not found\"}", await response.Content.ReadAsStringAsync());
});

Your suite sends three carts. A Mug (product 1) costs 12, a Pen (product 4) costs 2 and a Gift card (product 8) costs 50. The payment provider's test mode declines every payment over 1000. Work the expected answers out by hand, never with the code you are testing: a test that repeats the code's calculation repeats its bugs too.

POST /checkout  2 Mugs + 5 Pens   →  201  {"status":"paid","total":34}
POST /checkout  {"items": []}     →  400  {"error":"The cart is empty"}
POST /checkout  25 Gift cards     →  402  {"error":"Payment declined"}

When you run the code, the check runs your suite on the checkout, where all three tests must pass (3 tests: OK). Then it runs it on three broken copies of the checkout, and each copy must fail at least one test.

Your task: the starting code has SetUp, which stores app.GetTestClient() in client, and the test "checkout succeeds" with its cart. Finish that test and add two more, "empty cart" and "declined card". Each one posts its cart to /checkout with client.PostAsJsonAsync and checks the status code and the answer's text.


Assignment
Follow the Coding Tutorial to write a test suite for the checkout: a paid order, an empty cart and a declined card.


Hint
Every test has the same shape: post the cart with await client.PostAsJsonAsync("/checkout", cart), then one Assert.Equal for (int)response.StatusCode and one for await response.Content.ReadAsStringAsync(). Inside a C# string, write each " of the JSON as \". Work out each expected total on paper first.


STEP 1 OF 12
    Ctrl + Enter to check

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