JUnit Test Order Example
1. Introduction
One of the rarely used features in JUnit is the usage of @FixMethodOrder annotation. This is primarily used to indicate an order of test method calls in a specific JUnit Test case class. This is actually not a recommended practice cause we want method calls to be independent and arbitrary in nature. Test cases method should not be dependent on each other except for integration test cases.
Of course, this feature wouldn’t be included on the latest JUnit Library if not for it’s positive usage. Here are some examples that this feature might come in handy.
- Test case to execute specific service method to satisfy a functional scenario. Bad practice but in the real world application, this can be the case.
- Order of test case will also reflect on the representation in the report. It would certainly make sense from a report perspective that all test cases are defined in a specific order.
2. The Source
Here is a bit of example I made to showcase how can we order a specific test case.
package com.areyes1.jgc.tests;
import org.junit.Assert;
import org.junit.FixMethodOrder;
import static org.hamcrest.CoreMatchers.*;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.DEFAULT)
public class JUnitOrderSampleServiceTests {
@Test
public void testC() {
System.out.println("C");
int numberCResult = 0;
for (int i=0;i<1000;i++) {
//complex loop
numberCResult++;
}
Assert.assertThat(numberCResult,isA(Integer.class));
}
@Test
public void testA() {
System.out.println("A");
int numberAResult = 0;
for (int i=0;i<10000;i++) {
//complex loop
numberAResult++;
}
Assert.assertThat(numberAResult,isA(Integer.class));
}
@Test
public void testD() {
System.out.println("D");
int numberDResult = 0;
for (int i=0;i<100000;i++) {
//complex loop
numberDResult++;
}
Assert.assertThat(numberDResult,isA(Integer.class));
}
@Test
public void testB() {
System.out.println("B");
int numberBResult = 0;
for (int i=0;i<1000000;i++) {
//complex loop
numberBResult++;
}
Assert.assertThat(numberBResult,isA(Integer.class));
}
}
It starts with the annotation Download NOW!



