Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute order for test suite in junit

Tags:

java

junit

I am having a test suite which is having the following structure

TestClass1
      - testmethod1()
      - testmethod2()
      - testmethod3()
      - testmethod4() 
TestClass2
          - testmethod11()
          - testmethod22()
          - testmethod33()
          - testmethod44()

In the above structure i want to execute the testmethod4() as the final one. ie) executed at last. There is a annotation @FixMethodOrder which executes a method in order not the testclass. Is there any mechanism to maintain order in test class and testmethod together. With the @FixMethodOrder i can execute the method by renaming the name of the test method but i can't instruct junit to execute the test class as the final one(last one).

like image 733
Shriram Avatar asked Mar 04 '17 18:03

Shriram


People also ask

What is the correct order of execution in JUnit?

By default, JUnit runs tests using a deterministic but unpredictable order (MethodSorters. DEFAULT). In most cases, that behavior is perfectly fine and acceptable. But there are cases when we need to enforce a specific ordering.

What is the order in which JUnit annotations will run?

@Before and @After. @Before annotated method will run before each test method in the class. For example, if you have 3 test annotated method, @Before method will run 3 times before each @Test annotated method. On the other hand, @After annotated method will run after each test method in the class.

Which JUnit annotation allows you to define order of execution for the test methods?

Annotation Type FixMethodOrder. This class allows the user to choose the order of execution of the methods within a test class.


1 Answers

Though quoting @Andy again -

You shouldn't care about test ordering. If it's important, you've got interdependencies between tests, so you're testing behaviour + interdependencies, not simply behaviour. Your tests should work identically when executed in any order.

But if the need be to do so, you can try out Suite

@RunWith(Suite.class)

@Suite.SuiteClasses({
        TestClass2.class,
        TestClass1.class
})
public class JunitSuiteTest {
}

where you can either specify

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestClass1 {

    @AfterClass
    public void testMethod4() {

and then take care to name your method testMethod4 as such to be executed at the end OR you can also use @AfterClass which could soon be replaced by @AfterAll in Junit5.

Do take a look at Controlling the Order of the JUnit test by Alan Harder

like image 96
Naman Avatar answered Oct 14 '22 07:10

Naman