Tutorial :JUnit + Maven + Eclipse: Why @BeforeClass does not work?



Question:

I am using JUnit 4, Maven 2 and latest Eclipse. Problem is simple: I would like to perform some setup (connecting to a database) before my tests are executed.

I tried @BeforeClass in many different locations but Eclipse and Maven are ignoring this. Any help on accomplishing this initial setup?

Thanks!

public abstract class BaseTestCase extends TestCase {     @BeforeClass      public static void doBeforeClass() throws Exception {       System.out.println("No good @BeforeClass");       // DO THE DATABASE SETUP        }  }  

Now the tests extending BaseTestCase:

public class LoginActionTest extends BaseTestCase {     @Test   public void testNothing() {      System.out.println("TEST HERE");      assertEquals(true, true);   }  }  

Maven and Eclipse just ignore my @BeforeClass ??? Any other way to perform setup before tests?


Solution:1

Sergio, you were right about extending TestCase causing the problem. If you extend TestCase, JUnit treats your test class as an old (pre JUnit 4 class) and picks org.junit.internal.runners.JUnit38ClassRunner to run it. JUnit38ClassRunner does not know about @BeforeClass annotation. Check out source code of runnerForClass method of AllDefaultPossibilitiesBuilder and runnerForClass method of JUnit3Builder for more details.

Note: This problem is not related to Eclipse or Maven.


Solution:2

I suspect that you are running with JUnit 3. Try renaming your test to something which does not start with "test". If the test is no longer executing, you are using JUnit 3 (which assumes that test methods are methods which starts with "test").

Please post your Eclipse launch config.


Solution:3

I have similar problem and I fixed it by specifying surefile and junit versions explisitly:

<plugin>      <groupId>org.apache.maven.plugins</groupId>      <artifactId>maven-surefire-plugin</artifactId>      <version>2.8.1</version>      <dependencies>          <dependency>              <groupId>org.apache.maven.surefire</groupId>              <artifactId>surefire-junit47</artifactId>              <version>2.8.1</version>          </dependency>      </dependencies>      <configuration>          <parallel>methods</parallel>          <threadCount>10</threadCount>          <excludes>              <exclude>**/*IntegrationTest.java</exclude>          </excludes>      </configuration>  </plugin>  

More info is here: http://maven.apache.org/plugins/maven-surefire-plugin/examples/junit.html

It seems junit 3.8.1 version is used transiently through maven-resources-plugin and plexus-container-default. You can print dependency tree by calling mvn dependency:tree. I think there's no other way to make surefire use junit 4.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »