0

Execute Tests in Order in JUnit 4

Using @FixMethodOrder

To execute tests in a order in JUnit 4, annotate the class with @FixedMethodOrder passing one of enum MethodSorters items as parameter. Either one of the following can be used are parameter to @FixMethodOrder.

  • MethodSorters.NAME_ASCENDING: This sorts the test methods by the method name in the lexicographic order.
  • MethodSorters.DEFAULT: Does not guarantee the execution order.
  • MethodSorters.JVM: The sort order is determined by the JVM.

JUnit Tests Not using @FixMethodOrder

Without using @FixMethodOrder, the order of execution is not guaranteed.

The test execution order (varies in every execution) is as follows.

turreta-junit4-001-no-fixmethodorder-annotation

 

turreta-junit4-002-no-fixmethodorder-annotation

JUnit Tests using @FixMethodOrder

With a similar class annotated with @FixMethodOrder, we’d expect the execution order is by method name in ascending lexicographic order.

Expected execution order is:

turreta-junit4-003-with-fixmethodorder-annotation

 

turreta-junit4-004-with-fixmethodorder-annotation

Maven Test

Here is a screenshot from maven test via command line console:

turreta-junit4-005-mvn-test

Download the Codes

https://github.com/Turreta/junit4-fixmethodorder-example

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert