0
0
JUnittesting~5 mins

@AfterEach method in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the @AfterEach annotation in JUnit?
The @AfterEach annotation marks a method to be run after each test method. It is used to clean up or reset resources to keep tests independent.
Click to reveal answer
beginner
When is a method annotated with @AfterEach executed?
It runs immediately after each test method finishes, regardless of whether the test passed or failed.
Click to reveal answer
intermediate
Can multiple methods in the same test class have <code>@AfterEach</code> annotation?
Yes, multiple @AfterEach methods are allowed. They run in an undefined order after each test method.
Click to reveal answer
intermediate
How does @AfterEach differ from @AfterAll in JUnit?
<code>@AfterEach</code> runs after every test method, while <code>@AfterAll</code> runs once after all tests in the class have run.
Click to reveal answer
beginner
Give a simple example of a method using @AfterEach.
Example:<br>
  @AfterEach
  void cleanup() {
    // reset shared resources
  }
Click to reveal answer
What happens if a test method throws an exception? Does the @AfterEach method still run?
AOnly if the exception is caught inside the test.
BNo, <code>@AfterEach</code> only runs if the test passes.
CYes, <code>@AfterEach</code> runs even if the test fails or throws an exception.
DIt depends on the exception type.
Which annotation runs a method once after all tests in a class have finished?
A@BeforeEach
B@AfterAll
C@AfterEach
D@BeforeAll
Can you have more than one @AfterEach method in a test class?
AOnly if they are static methods.
BNo, only one is allowed.
CYes, but only if they have different names.
DYes, multiple are allowed and run in any order.
What is a common use case for @AfterEach methods?
ATo clean up or reset resources after each test.
BTo initialize test data before each test.
CTo run tests in parallel.
DTo skip tests conditionally.
If you want to release a database connection after each test, which annotation should you use on the cleanup method?
A@AfterEach
B@BeforeEach
C@BeforeAll
D@AfterAll
Explain the role and timing of the @AfterEach method in JUnit testing.
Think about what happens after every test finishes.
You got /3 concepts.
    Describe the difference between @AfterEach and @AfterAll annotations.
    Consider how often each runs during the test lifecycle.
    You got /3 concepts.