Until now you checked your shop by hand: send a request, read the answer, decide if it's right. A test is code that does this for you, every time you run it, so you notice at once when a change breaks something. C# developers usually write tests with xUnit; this lesson gives you its tools, with xUnit's names, ready to use.
Test(name, async () => { … }) writes one test down, and the check runs every test written down that way. Assert.Equal(expected, actual) checks that two values are equal: if they differ, the test fails and shows both. Here is a test for a small function, not for the shop:
int AddShipping(int price) {
return price + 5;
}
Test("add shipping", async () => {
Assert.Equal(15, AddShipping(10));
});
app.GetTestClient() gives a test client: an HttpClient that sends requests to the shop app. await client.GetAsync(path) gives back the response, with the status in response.StatusCode; (int) turns it into a number like 200. The shop answers GET /products with 200 and its four products. The check runs your test on the shop, then on a broken copy that lost its GET /products route, and must print:
Your tests on the shop:
products answer 200 ... ok
1 test: OK
Your tests on a copy that lost its GET /products route:
products answer 200 ... FAIL
Assert.Equal() Failure: Expected 200, Actual 405
1 test: 1 failed, so they caught this bug
Your task: write one test, "products answer 200", that sends GET /products with a test client and checks that the status code is 200.
Assignment
Follow the Coding Tutorial to write your first test: a Test call, a test client, a request and one check.
Hint
In Assert.Equal, put what you expect first and what you got second. A test with no check passes on any shop, even a broken one, so don't forget the last line.
Free plan: 30 tutor messages. PRO is unlimited.
