Leveraging Annotations in Test
The purpose of leveraging annotations (or hooks) is so you can set up an environment and have the appropriate amount of data seeded for the tests to use. Common JUnit hooks are covered here. Any modern testing framework leverages this basic model.
A quick rundown of when to use what:
BeforeClass
BeforeClass
(or equivalent) when you want something to execute once for the test class,
before any tests run, and before the BeforeTest
code runs.
This is where you set up your environment and prepare any data. Any data that is shared between all tests belongs in here.
Before
Before
will run before each test method.
If you have 3 tests, whatever is in Before
will run 3 times in total.
This is where data preparation should go if a fresh set of data is needed for every test. If this is an E2E (web) test, this is also where the browser should be opened and navigation to the appropriate page for testing should occur.
After
After
runs after each test method.
This is where data cleanup should go if you are creating new data before each test.
AfterClass
AfterClass
runs after all of the tests have finished, and after the last execution of After
.
This is where data cleanup should happen for anything that was created in BeforeClass
.
If having a pristine environment is a goal, then this is where you should try to delete
anything that was created but not successfully deleted.
If you’re unable to delete it still, you can log the information so it’s not lost. It may require someone to take a look into why something is failing. This often uncovers bugs around edge cases that weren’t thought about. It also surfaces many bugs caused by unexpected missing (or present) data.