Skip to content

Instantly share code, notes, and snippets.

@bsharathchand
Created October 28, 2014 20:32
Show Gist options
  • Save bsharathchand/12a5d5abcd0c0d3fe7c8 to your computer and use it in GitHub Desktop.
Save bsharathchand/12a5d5abcd0c0d3fe7c8 to your computer and use it in GitHub Desktop.
JUnit method ordering

Junit Test Execution Order

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

Sample Code


@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.

  1. addDoubles()
  1. addIntegers()
  2. addStrings()

Hope this helps, and if otherwise feel free to comment on this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment