[JAVA] Control test order in Junit4 with enumeration

Overview

JUnit does not guarantee the execution order of the methods defined by the @Test annotation.

Therefore, create the following three classes to control the execution order.

As a process flow, ʻOrderedRunner was added to each test method when executing the test. The flow is to control the execution order by reading the setting value of ʻOrder.

TestMethod.java



public enum TestMethod {
    strArrayIsNullTest,
    strIsNullTest
};

Order.java



import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Order {
    TestMethod order();
}

OrderedRunner.java


import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;

public class OrderedRunner extends BlockJUnit4ClassRunner {
    public OrderedRunner(Class<?> klass) throws InitializationError  {
        super(klass);
    }

    @Override
    protected List<FrameworkMethod> computeTestMethods() {
        List<FrameworkMethod> list = super.computeTestMethods();
        Collections.sort(list, new Comparator<FrameworkMethod>() {
            @Override
            public int compare(FrameworkMethod f1, FrameworkMethod f2) {
                Order o1 = f1.getAnnotation(Order.class);
                Order o2 = f2.getAnnotation(Order.class);

                if (o1 == null || o2 == null){
                    return -1;
                }
                return o1.order().ordinal() - o2.order().ordinal();
            }
        });
        return list;
    }
}

Practice

Foo.java


public class Foo {
    public static boolean isNull(String[] arg) {
        return arg == null;
    }

    public static boolean isNull(String str) {
        return str == null || str.length() == 0 || str.equals("");
    }
}

FooTest.java


import static org.junit.Assert.*;

import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(OrderedRunner.class)
public class FooTest {

    @Test
    @Order(order=TestMethod.strArrayIsNullTest)
    public void strArrayIsNullTest() {
        String[] arg = {"test"};
        assertFalse(Foo.isNull(arg));
        System.out.println("strArrayIsNullTest OK");
    }

    //Even if you add a test, the order is guaranteed by adding an element to TestMethod.
    /**
     * @Test
     * @Order(order=TestMethod.reservationsTest)
     * public void reservationsTest();
     */

    @Test
    @Order(order=TestMethod.strIsNullTest)
    public void strIsNullTest() {
        String str = "test";
        assertFalse(Foo.isNull(str));
        System.out.println("strIsNullTest OK");
    }
}

Reference material

Recommended Posts

Control test order in Junit4 with enumeration
Unit test with Junit.
Test Web API with junit
Test private methods in JUnit
Test private methods in JUnit
Output JUnit test report in Maven
[Java] Test private methods with JUnit
Test Spring framework controller with Junit
JUnit unit test pre-processing and post-processing order
How to filter JUnit Test in Gradle
Getting Started with Parameterization Testing in JUnit
How to test private scope with JUnit
JUnit 5 gradle test fails with lombok annotation
Java automated test implementation with JUnit 5 + Gradle
How to test private methods with arrays or variadic arguments in JUnit
[Java] How to test for null with JUnit
[CircleCI 2.0] [Java] [Maven] [JUnit] Aggregate JUnit test results with CircleCI 2.0
Test controller with Mock MVC in Spring Boot
How to test interrupts during Thread.sleep with JUnit
Easy JUnit test of Elasticsearch 2018 version with embedded-elasticsearch
JUnit 5: How to write test cases in enum
Test code using mock with JUnit (EasyMock center)
Refactoring in JUnit
Visualize test methods running in TestNG with listeners
Mixin test cases with JUnit 5 and default methods
How to sort in ascending / descending order with SQLite
Setup with initial test data inserted in Db2 / DB container
Get the name of the test case in the JUnit test class
Test the contents of an Excel file with JUnit
Implement test doubles in JUnit without using external libraries
[JUnit 5 compatible] Write a test using JUnit 5 with Spring boot 2.2, 2.3
[JUnit 5] Write a validation test with Spring Boot! [Parameterization test]
WebAPI unit test and integration test with SpringBoot + Junit5, 4 patterns
I wrote a test with Spring Boot + JUnit 5 now
Integration Test with Gradle
[Rails] Test with RSpec
Test Nokogiri with Rspec.
Automatically test with Gauge
Load test with JMeter
Testing request sending and receiving logic with MockWebServer in JUnit
[Java] I want to test standard input & standard output with JUnit