Dotan Raz
Dotan Raz

Reputation: 453

Execute Junit tests using Maven

I have 2 classes under src/test/java that I want to run: scen1.class and scen2.class. Both of these have @Test annotated methods.

I have another class called JunitDefinitions.class that has only @Before, @After, @BeforeClass and @AfterClass methods (no @Test). This is also under src/test/java but under a different package.

Assuming I have the default pom.xml, what should I add to it in order to be able to execute all these 3 classes?

Upvotes: 1

Views: 485

Answers (2)

Naman
Naman

Reputation: 32036

Apart from the renaming of your classes as something like Scen1Test.java and Scen2Test.java as suggested by @viniciusartur, which shall help Maven to recognize the test classes to execute them using surefire-plugin.

Another point to note here is that the reason due to which the @Before, @BeforeClass, @After etc are not executed independently without a @Test method is that only

The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method.

From the documentation of @Before in JUnit

Annotating a public void method with @Before causes that method to be run before the Test method. The @Before methods of superclasses will be run before those of the current class.

So inferring as this, while annotations are processed, if there is no @Test annotation present in the class under /src/test/java(relative to the question based on maven), no further annotations are meaningful to be processed.

Just to note, if you extend this class with another SubClassTest.java consisting of a @Test method, all these methods would be executed then. Since they are processed based on what(@Test) to act on to.

Upvotes: 1

viniciusartur
viniciusartur

Reputation: 161

  • Rename your test classes to Scen1Test.java and Scen2Test.java or include JunitFW.java, Scen1.java and Scen2.java using <includes> configuration, as it's described in the documentation.
  • The class JunitFW only contains a @Before, so it's not detected as a Test. You have to move the @Before to a class containing @Test or include a @Test in JunitFW class and rename it to JunitFWTest to make it work.

By default, the Surefire Plugin will automatically include all test classes with the following wildcard patterns:

"**/Test*.java" - includes all of its subdirectories and all Java filenames that start with "Test".
"**/*Test.java" - includes all of its subdirectories and all Java filenames that end with "Test".
"**/*Tests.java" - includes all of its subdirectories and all Java filenames that end with "Tests".
"**/*TestCase.java" - includes all of its subdirectories and all Java filenames that end with "TestCase".

Upvotes: 1

Related Questions