Tests must not depend on each other. If all your tests use the same shop, they share its list of products: a Plant added by one test is still there when the next test runs. Then a test can pass or fail just because of which test ran before it.
The check has a fix: SetUp. You hand it a function, and the check calls that function before each test, every time, so it's the place to build fresh data. What it stores in a variable declared at the top, the test that runs next can use.
List<string> cart = null;
SetUp(() => {
cart = new List<string>();
});
Test("add", async () => {
cart.Add("Mug");
Assert.Equal(1, cart.Count);
});
Test("empty", async () => {
Assert.Equal(0, cart.Count);
});
"add" runs first and puts a Mug in the cart, yet "empty" still finds an empty cart: SetUp made a new one before it. In the shop, CreateApp() does that job: each call builds a new shop with its own four products. With a new shop in every test, your two tests get these answers in any order:
add product: POST /products (a Plant) → {"id":5, …}
count products: GET /products → a list of 4 products
The check runs your tests, then again in the opposite order, then once more with every test on the same shop, to show what fresh data saves you from. It must print:
Your tests on the shop:
add product ... ok
count products ... ok
2 tests: OK
Your tests again, in the opposite order:
count products ... ok
add product ... ok
2 tests: OK
Your tests if every test got the same shop:
add product ... ok
count products ... FAIL
Assert.Equal() Failure: Expected 4, Actual 5
2 tests: 1 failed
Your task: above the first test, call SetUp with a function that builds a new shop with CreateApp(), keeps it in app, and stores its test client in the client declared at the top. Then, below "add product", write a test named "count products": GET /products with client and check that the list has 4 products.
Assignment
Follow the Coding Tutorial to give every test a fresh shop in SetUp, then test that the shop still has 4 products.
Hint
SetUp's function has no async. Store the client with client = …, without var, so the tests use the client from the first line. GetArrayLength() counts the items of a JSON list.
Free plan: 30 tutor messages. PRO is unlimited.
