Software Development

Execute Tests in Order in JUnit 4

Using @FixMethodOrder

[wp_ad_camp_5]

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.

[wp_ad_camp_4]

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

[wp_ad_camp_3]

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

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like