I have a test case where I add an entity, update it and delete the same. Hence, the order of execution is important here. I want it to be :
- Create
- Update
- Delete
Strangely, for just one test case ( out of 15) , JUnit executes it in the following order :
- Delete
- Update
- Create .
How do I tell JUnit to execute them in a specific order ? In other cases, JUnit works totally fine ( executing serially ) . And why does JUnit behave weirdly in this one case ?
Relevant code snippet below :
private static Date date;
private static int entity;
static Parking p;
public ParkingTests(String name) {
super(name);
}
public void testAdd() throws Exception {
//Add code here
}
public void testUpdate() throws Exception {
//update code here
}
public void testDelete() throws Exception {
//delete code here
}
}
It gets weirder. I run a lot of test cases as part of a suite. If I run just the Parking case, the order is maintained. If I run it along with others, it is sometimes maintained, sometimes not !
Your kind of situation is awkward, as it feels bad to keep duplicating work in order to isolate the tests (see below) – but note that most of the duplication can be pulled out into
setUpandtearDown(@Before,@After) methods, so you don’t need much extra code. Provided that the tests are not running so slowly that you stop running them often, it’s better to waste a bit of CPU in the name of clean testing.The alternative is to stick everything into one test with multiple asserts, but this is harder to understand and maintain, and gives a bit less information when a test fails:
Testing with databases or collections or storage of any kind is tricky because one test can always affect other tests by leaving junk behind in the database/collection. Even if your tests don’t explicitly rely on one another, they may still interfere with one another, especially if one of them fails.
Where possible, use a fresh instance for each test, or wipe the data, ideally in as simple a way as possible – e.g. for a database, wiping an entire table is more likely to succeed than a very specific deletion that you might accidentally get wrong.
Update: It’s usually better to wipe data at the start of the test, so one failed test run doesn’t affect the next run.