Recall & Review
beginner
What does the
@TestInstance(Lifecycle.PER_CLASS) annotation do in JUnit?It tells JUnit to create only one instance of the test class and reuse it for all test methods, instead of creating a new instance for each test method.Click to reveal answer
intermediate
Why might you use
@TestInstance(Lifecycle.PER_CLASS) instead of the default lifecycle?To share state or expensive setup between test methods, reducing repeated initialization and improving test performance.
Click to reveal answer
intermediate
How does
@BeforeAll behave differently when using @TestInstance(Lifecycle.PER_CLASS)?With PER_CLASS lifecycle, <code>@BeforeAll</code> methods can be non-static because the same test instance is reused.Click to reveal answer
beginner
What is the default test instance lifecycle in JUnit 5?
The default lifecycle is <code>PER_METHOD</code>, which creates a new test class instance for each test method.Click to reveal answer
advanced
What is a potential risk of using
@TestInstance(Lifecycle.PER_CLASS)?Tests might become dependent on each other if shared state is modified, leading to flaky or unreliable tests.
Click to reveal answer
What happens when you annotate a JUnit 5 test class with
@TestInstance(Lifecycle.PER_CLASS)?✗ Incorrect
PER_CLASS lifecycle means one instance is reused for all test methods.
Which method can be non-static when using
@TestInstance(Lifecycle.PER_CLASS)?✗ Incorrect
With PER_CLASS, @BeforeAll can be non-static because the same instance is used.
What is the default lifecycle of test instances in JUnit 5?
✗ Incorrect
JUnit 5 creates a new instance per test method by default (PER_METHOD).
What is a common reason to choose PER_CLASS lifecycle?
✗ Incorrect
PER_CLASS allows sharing setup or state to improve performance.
What risk does PER_CLASS lifecycle introduce?
✗ Incorrect
Shared state can cause tests to affect each other, leading to flaky tests.
Explain how the
@TestInstance(Lifecycle.PER_CLASS) annotation changes the lifecycle of test instances in JUnit 5.Think about how many times the test class is created.
You got /4 concepts.
Describe the benefits and risks of using the PER_CLASS lifecycle in JUnit testing.
Consider both positive and negative effects on test design.
You got /4 concepts.