Tests must not depend on each other. If all your tests talk to the same shop, they share its data: 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 test runner has a fix: a method named setUp. The runner calls it before each test, every time, so it's the place to build fresh data. What setUp stores in a field of the class, the test that runs next can use.
class CartTests extends TestCase {
List<String> cart;
void setUp() {
cart = new ArrayList<>();
}
void testAdd() {
cart.add("Mug");
assertEquals(1, cart.size());
}
void testEmpty() {
assertEquals(0, cart.size());
}
}
testAdd runs first and puts a Mug in the cart, yet testEmpty 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, and app.testClient() gives a client for it. With a new shop in every test, your two tests get these answers in any order:
testAddProduct: POST /products (a Plant) → {"id": 5, …}
testCountProducts: 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:
testAddProduct ... ok
testCountProducts ... ok
2 tests: OK
Your tests again, in the opposite order:
testCountProducts ... ok
testAddProduct ... ok
2 tests: OK
Your tests if every test got the same shop:
testAddProduct ... ok
testCountProducts ... FAIL
AssertionError: expected: <4> but was: <5>
2 tests: 1 failed
Your task: below the client field of ProductTests, write setUp: keep createApp() in ShopApp app, and store app.testClient() in the client field. Then, below testAddProduct, write testCountProducts: GET /products with client, reading a List, 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
The name is setUp, with a capital U. Write client = app.testClient(); with no type in front: with a type, you'd make a new local variable and the field would stay null. size() counts the items of a list.
Free plan: 30 tutor messages. PRO is unlimited.
