为什么不是我的@BeforeClass方法运行?

我有以下代码:

@BeforeClass public static void setUpOnce() throws InterruptedException { fail("LOL"); } 

和其他各种方法,无论是@Before,@After,@ Test或@AfterClass方法。

testing在启动时不会失败,因为它看起来应该是这样。 有人能帮助我吗?

我有JUnit 4.5

该方法在立即调用setUp()(注释为@before)时失败。 Class def是:

 public class myTests extends TestCase { 

不要扩展TestCase并同时使用注释!
如果您需要创build一个包含注释的testing套件,请使用RunWith注释,如下所示:

 @RunWith(Suite.class) @Suite.SuiteClasses({ MyTests.class, OtherTest.class }) public class AllTests { // empty } public class MyTests { // no extends here @BeforeClass public static void setUpOnce() throws InterruptedException { ... @Test ... 

(按惯例:带有大写字母的类名)

该方法必须是静态的 ,不能直接调用失败(否则其他方法将不会执行)。

以下类显示了所有标准的JUnit 4方法types:

 public class Sample { @BeforeClass public static void beforeClass() { System.out.println("@BeforeClass"); } @Before public void before() { System.out.println("@Before"); } @Test public void test() { System.out.println("@Test"); } @After public void after() { System.out.println("@After"); } @AfterClass public static void afterClass() { System.out.println("@AfterClass"); } } 

输出是(不奇怪):

 @BeforeClass @Before @Test @After @AfterClass 

确保:

  • 您的testing类不从TestCaseinheritance
  • @BeforeClass方法是静态的
  • testing类层次结构中没有多个@BeforeClass方法(只有最专门化的@BeforeClass方法将被执行)

为了使注释前的函数能够运行,我必须执行以下操作:如果你使用Maven,添加一个依赖到Junit 4.11+:

  <properties> <version.java>1.7</version.java> <version.log4j>1.2.13</version.log4j> <version.mockito>1.9.0</version.mockito> <version.power-mockito>1.4.12</version.power-mockito> <version.junit>4.11</version.junit> <version.power-mockito>1.4.12</version.power-mockito> </properties> 

和依赖:

  <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${version.junit}</version> <scope>test</scope> </dependency> . . . </dependencies> 

确保您的Junittesting类不扩展TestCase类,因为这会导致与旧版本重叠:

 public class TuxedoExceptionMapperTest{ protected TuxedoExceptionMapper subject; @Before public void before() throws Exception { subject = TuxedoExceptionMapper.getInstance(); System.out.println("Start"); MockitoAnnotations.initMocks(this); } }