Video in progress
Why should tests not depend on each other, and be able to pass in any order?
JUnit doesn't guarantee a run order, and it can run tests in parallel. If one test relies on a state left by another, it fails when the order changes or when you run it alone.
📖 Answer
A typical mistake:
class UserRepoTest {
static Long createdId;
@Test
void create() { createdId = repo.save(new User("Ali")).getId(); }
@Test
void find() { assertNotNull(repo.findById(createdId)); } // passes only if it runs after create
}
If you click and run only find in the IDE, it fails. If the order is different in CI, it fails. Worst of all, this kind of bug shows up as "sometimes passes, sometimes doesn't".
The right way: each test prepares the data it needs itself, in @BeforeEach or inside the test.
JUnit 5 has @TestMethodOrder(OrderAnnotation.class) and @Order(1). They're sometimes used in step-by-step integration scenarios, but if you feel the need for them in plain unit tests, it's a sign the test design is broken.
Sign up to mark studied questions and save your progress.