1

We have recently upgraded on Java 7, but after that our suite is facing weird issue that it is first executing method with @After annotation and then methods with @Test annotation. Any help will appreciated. Thanks in advance

EDIT: This is the code from the comment:

public class TestClasse extends TestCase {
  @Test public void testLogin(){ System.out.println("TestCase1");    }
  @Test public void testLogout(){ System.out.println("TestCase2");   }
  @After public void testGenerateReport(){ System.out.println("testCase3") }
}
Simulant
  • 19,190
  • 8
  • 63
  • 98
Aarvy
  • 13
  • 2
  • 1
    Could you show some relevant code? – LaurentG Aug 16 '13 at 06:32
  • public class TestClasse extends TestCase { @ Test public void testLogin(){ System.out.println("TestCase1"); } @ Test public void testLogout(){ System.out.println("TestCase2"); } @ After public void testGenerateReport(){ System.out.println("testCase3") } } Output: testCase3 TestCase1 TestCase3 – Aarvy Aug 16 '13 at 07:21

1 Answers1

5

This is your code:

public class TestClasse extends TestCase {
@Test public void testLogin(){ System.out.println("TestCase1");  }
@Test public void testLogout(){ System.out.println("TestCase2");     }
@After public void testGenerateReport(){ System.out.println("testCase3") }
}

You are using JUnit 3 (because you're extending TestCase), so JUnit is running all of the methods which begin with 'test'.

The solution: don't extend TestCase, and make sure that your classpath includes JUnit 4 (4.11 is the latest). Also, to avoid confusion, don't name your @After methods testXXX.

Why did it stop working when you upgraded to Java 7?

When you are searching for methods in Java 6 and before, in most cases the JVM returns the methods in the order in which they are declared in the source file (in your case testLogin, testLogout, testGenerateReport). This changed with Java 7, so that the methods are returned in a different unpredictable order (see my answer to Has JUnit4 begun supporting ordering of test? Is it intentional?). So, when you upgraded to Java 7, the order in which the methods were found and executed changed - and your @After was executed first.

For more background to this issue, see Sort test methods for predictability and SortMethodsWith allows the user to choose the order of execution of the methods within a test class.

Community
  • 1
  • 1
Matthew Farwell
  • 60,889
  • 18
  • 128
  • 171