If any time, you have run junit tests and executed them on your code, you should have already observed that the test execution order for JUnit is not what you expected to be. The reason for this behaviour of Junit is because it uses Java Reflections to select and execute the test methods.
Did you ever wanted to execute your Unit tests in deterministic order? If yes we have got a way to do that in JUnit 4.
Inorder to exuecute the Unit tests in a fixed or deterministic order, you have got to decorate your TestClass with @FixedOrder
annotation.
@FixedOrder
annotation will take the parameter of the MethodSorters
enum for sorting the test method execution order.
MethodSorters enum has the following constants for sorting.
- NAME_ASCENDING -> Uses the dictionary ordering of the test methods based on name
- DEFAULT -> runs in a fixed order, but undeterminitic
- JVM -> will not run in a fixed order, and is definitely undeterministic
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestAddition(){
@Test
public void addIntegers(){
// Test Code
}
@Test
public void addDoubles(){
// Test Code
}
@Test
public void addStrings(){
// Test Code
}
}
When you try running this sample code, the execution order of the testmethods in the TestAddtion
class is always fixed and is as given below.
- addDoubles()
- addIntegers()
- addStrings()
Hope this helps, and if otherwise feel free to comment on this.