Newer
Older
labs / tiddlers / content / labs / lab02 / _Labs_02_Testing with Persistent Data.md

So far we have not used the @AfterEach/tearDown method. We have not needed to since we were creating brand new objects in the setUp for each test, and there is no persistent state anywhere in the system (such as databases or file stores).

We can simulate persistent state by making the items collection in the Invoice class static.

Modify the Invoice class so that the items field declaration now has the static keyword. The result should look like:

private static Collection<InvoiceItem> items = new HashSet<>();

Static fields do not belong to any object --- they are part of the class itself. This means that any changes to the field will be reflected in all objects including brand new ones. All of our invoice objects will now all be sharing a single items collection.

Run the tests. Uh oh --- failures. If you expand the messages under the failed test you will see that the hasSize tests are failing due to the items collection having too many items in it.

Since we have three tests, and the setUp method is adding two items for each test, we now have 6 item objects being added to the static (shared) items collection. One of them is removed in the removeItem test, so we now potentially have 5 items in the collection instead of the 2 that we had prior to making the field static. Basically, test data relating to one test is impacting other tests which violates the "tests should be independent" rule.

We now need to use the tearDown method to clean up after each test to ensure that each test is independent.

Add the following code to the tearDown method of the InvoiceTest class:

invoice.removeItem(item1);
invoice.removeItem(item2);
invoice.removeItem(item3);

Run the tests again. We should be good again.

Run the tests a few more times to verify that the results are repeatable.

Run the tests for the entire project by using <

Test Project">>. We want to be sure that there are no weird interactions caused by tests interfering with each other.