Providing order to Test class execution Java

664 Views Asked by At

I have three test classes to test my controller, service and Kafka Messaging. When I run the Kafka messaging standalone, it works. But when I run all my test files together, the Kafka test class passes as long as it is the first one that gets executed otherwise it fails.

I would like to order the execution of test classes by making sure that Kafka test class always is the first one to execute.

How can I achieve that? With Test suites?? Is there any other way? My application is built using Micronaut, Java 8.

2

There are 2 best solutions below

0
On

The order of tests run by JUnit is undefined. You must write your tests such that they can run independently.

First, Stop pretending that an integration test (i.e. one that actually calls Kafka) is a unit test. If you are calling something outside the method being tested, then you are running integration tests.

Possible solutions include:

  1. Use mocks for the Kafka stuff and thus create an actual unit test.
  2. To continue with Integration testing, create one class with one method that is annotated as a @Test and have it call methods in your existing "test classes" in the desired order.
0
On

Try using @OrderWith annotation which helps in test execution order

@OrderWith(Alphanumeric.class)
public class TestMethodOrder {
    .....
}

The above code will run the tests in the Alphanumeric order of method names.

We can also use @FixMethodOrder annotation to mention the order in which methods has to be sorted and executed. Currently, there is three options

  • MethodSorters.DEFAULT

  • MethodSorters.NAME_ASCENDING

  • MethodSorters.JVM

    @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestMethodOrder { ..... }

References: https://github.com/junit-team/junit4/wiki/Test-execution-order