【问题标题】:@After annotation is running first while using JUnit with JAVA 7在将 JUnit 与 JAVA 7 一起使用时,@After 注释首先运行
【发布时间】:2013-08-16 06:23:39
【问题描述】:

我们最近升级了 Java 7,但之后我们的套件面临一个奇怪的问题,即它首先执行带有 @After 注释的方法,然后是带有 @Test 注释的方法。 任何帮助将不胜感激。 提前致谢

编辑:这是评论中的代码:

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") }
}

【问题讨论】:

  • 你能显示一些相关的代码吗?
  • 公共类 TestClasse 扩展 TestCase { @Test public void testLogin(){ System.out.println("TestCase1"); } @Test public void testLogout(){ System.out.println("TestCase2"); } @ 之后 public void testGenerateReport(){ System.out.println("testCase3") } } 输出:testCase3 TestCase1 TestCase3

标签: java junit


【解决方案1】:

这是你的代码:

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") }
}

您正在使用 JUnit 3(因为您正在扩展 TestCase),因此 JUnit 正在运行所有以“test”开头的方法。

解决方案:不要扩展 TestCase,并确保您的类路径包含 JUnit 4(4.11 是最新的)。此外,为避免混淆,请勿将您的 @After 方法命名为 testXXX。

为什么升级到 Java 7 后它停止工作?

当您在 Java 6 及之前的版本中搜索方法时,在大多数情况下,JVM 按照它们在源文件中声明的顺序返回方法(在您的情况下为 testLogin、testLogout、testGenerateReport)。这在 Java 7 中发生了变化,因此方法以不同的不可预测的顺序返回(请参阅我对 Has JUnit4 begun supporting ordering of test? Is it intentional? 的回答)。因此,当您升级到 Java 7 时,查找和执行方法的顺序发生了变化 - 您的 @After 首先被执行。

有关此问题的更多背景信息,请参阅 Sort test methods for predictabilitySortMethodsWith allows the user to choose the order of execution of the methods within a test class

【讨论】:

  • 同样(使用 JUnit 4 运行时)@After 在每个单独的 @Test 方法之后运行,而不是在执行所有测试之后运行。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-06
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
相关资源
最近更新 更多