1

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.

Software Engineer
  • 15,457
  • 7
  • 74
  • 102
Abhinav Mehrotra
  • 543
  • 2
  • 8
  • 17
  • 2
    You should really write your tests so that they execute independently in any order. – Software Engineer May 21 '21 at 14:43
  • Fix your tests. They’re broken. The ordering is a symptom of the underlying cause. – Boris the Spider May 21 '21 at 14:43
  • 2
    Does this answer your question? [How to run test methods in specific order in JUnit4?](https://stackoverflow.com/questions/3693626/how-to-run-test-methods-in-specific-order-in-junit4) – Software Engineer May 21 '21 at 14:44
  • @SoftwareEngineer I understand the underlying principle of running tests independently. But in this case it is the Kafka Integration test that is causing the issue which is a bit inconsistent. Also, the link you have posted is about test methods. I am looking for ordering Test Classes. – Abhinav Mehrotra May 21 '21 at 14:56
  • Cool -- thanks for pointing out the difference, I've revoked my close vote. – Software Engineer May 21 '21 at 14:56
  • Maybe https://stackoverflow.com/questions/19177195/running-junit4-test-classes-in-specified-order ? – Software Engineer May 21 '21 at 14:59

2 Answers2

1

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.
DwB
  • 37,124
  • 11
  • 56
  • 82
0

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