2010-07-18 22 views
8

我正在使用JUnit 4,Maven 2和最新的Eclipse。问题很简单:我想在执行测试之前执行一些设置(连接到数据库)。JUnit + Maven + Eclipse:为什么@BeforeClass不起作用?

我在许多不同的位置尝试了@BeforeClass,但Eclipse和Maven忽略了这一点。任何帮助完成此初始设置?

谢谢!

public abstract class BaseTestCase extends TestCase { 

@BeforeClass 
    public static void doBeforeClass() throws Exception { 

    System.out.println("No good @BeforeClass"); 

    // DO THE DATABASE SETUP 

    } 
} 

现在延长BaseTestCase测试:

public class LoginActionTest extends BaseTestCase { 

@Test 
public void testNothing() { 

    System.out.println("TEST HERE"); 

    assertEquals(true, true); 
} 
} 

Maven和Eclipse的只是忽略我的@BeforeClass ???在测试之前执行设置的任何其他方式?

+0

能否请您确认如何从Eclipse内启动测试用例?你在使用JUnit4吗? – ShiDoiSi 2010-07-18 07:14:39

+0

我正在使用JUnit 4.我使用Run As ...启动 - > JUnit Test ...问题与扩展TestCase有关。如果你放弃延续这个课程,那么你很好。你实际上不需要这个类,因为你可以导入Assert类来执行检查......不要扩展TestCase,并且所有事情都按预期工作...... – TraderJoeChicago 2010-07-18 10:05:07

回答

11

Sergio,你说得对扩展TestCase导致问题是正确的。如果扩展TestCase,JUnit会将您的测试类视为旧的(JUnit 4之前的类),并选择org.junit.internal.runners.JUnit38ClassRunner来运行它。 JUnit38ClassRunner不知道有关@BeforeClass注释。请参阅runnerForClass方法AllDefaultPossibilitiesBuilderrunnerForClass方法JUnit3Builder的源代码以了解更多详情。

注意:此问题与Eclipse或Maven无关。

+0

是的。我放弃了扩展TestCase,一切正常。 – TraderJoeChicago 2010-07-18 10:02:43

1

我怀疑你正在运行JUnit 3.尝试将你的测试重命名为不以“test”开头的东西。如果测试不再执行,则使用JUnit 3(假定测试方法是以“test”开头的方法)。

请发布您的Eclipse启动配置。

1

我有类似的问题,我通过explisitly指定surefile和JUnit版本修复它:

<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> 

更多信息是在这里:http://maven.apache.org/plugins/maven-surefire-plugin/examples/junit.html

看来JUnit的3.8.1版本通过maven-暂时使用resources-plugin和plexus-container-default。您可以通过调用mvn依赖关系打印依赖关系树:树。我认为没有其他方法可以确保使用junit 4.

相关问题