How to Run JUnit Tests in Order

In this tutorial, I am going to share with you how to make your JUnit tests run in order. And if you are interested to learn more about testing your RESTful Web Services with JUnit and Rest Assured check this list of tutorials: Building and Testing RESTful Web Services

JUnit Method Sorters

To run Unit tests in a specific order we can use the @FixMethodOrder annotation and the MethodSorters class which has three options: 

  • MethodSorters.DEFAULT – Sorts the test methods in a deterministic, but not predictable, order
  • MethodSorters.NAME_ASCENDING – Sorts the test methods by the method name, in lexicographic order, with {@link Method#toString()} used as a tiebreaker
  • MethodSorters.JVM – Leaves the test methods in the order returned by the JVM. Note that the order from the JVM may vary from run to run.

Run JUnit Tests in Order:  From Top to Bottom

For me to be able to run my JUnit tests from top to bottom in the order I will use the MethodSorters.NAME_ASCENDING option. And to guarantee my methods are sorted in an ascending order I will give them very simple names: a(), b(), c(), d() and etc. This will make your JUnit test to always run in an order you want. Have a look at the below example. 

package com.appsdeveloperblog.app.ws.test.mobileappwstest;

import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class UsersWebServiceEndpointTest {
 
    @Before
    public void setup() {
        System.out.println("This method will run before each test method");
    }

    /*
     * You can add method description here
     */
    @Test 
    public void a() 
    {  
        System.out.println("This method will run first");
    }
    
    /*
     * You can add method description here
     */ 
    @Test 
    public void b() {
       System.out.println("This method will run second"); 
    }
    
    /*
     * You can add method description here
     */ 
    @Test 
    public void c() {
       System.out.println("This method will run third"); 
    }

    /*
     * You can add method description here
     */ 
    @Test 
    public void d() {
       System.out.println("This method will run last"); 
    }

}

I hope this tutorial was helpful to you. Have a look at the below list of video courses that teach how to test your code and hopefully ne of them might be of a great value to you.