在我的项目中,我必须在所有测试之前进行一些存储库设置。这是使用一些棘手的静态规则来完成的。然而,在所有测试之后我不知道如何进行清理。我不想保留一些神奇的静态数字来引用所有测试方法的数量,我应该一直维护它。
最受赞赏的方法是添加一些侦听器,该侦听器将在所有测试后调用。 JUnit4 中是否已经有任何接口?
编辑:这与@BeforeClass和@AfterClass无关,因为我必须知道用@AfterClass注释的方法是否是最后一次调用。
我建议使用 org.junit.runner.notification.RunListener,例如:
public class TestListener extends RunListener {
@Override
public void testRunStarted(Description description) throws Exception {
// Called before any tests have been run.
}
@Override
public void testRunFinished(Result result) throws Exception {
// Called when all tests have finished
}
}
直接在 JUnit java 文档中阅读更多内容。 您甚至可以通过将以下代码添加到插件配置中来使用 Maven 的surefire(单元测试)插件或failsafe 插件(集成测试):
<properties>
<property>
<name>listener</name>
<value>com.innovatrics.afismq.it.TestListener</value>
</property>
</properties>
我正在使用 JUnit 4.9。这会有帮助吗?:
import junit.framework.TestCase;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({First.class,Second.class,Third.class})
public class RunTestSuite extends TestCase {
@BeforeClass
public static void doYourOneTimeSetup() {
...
}
@AfterClass
public static void doYourOneTimeTeardown() {
...
}
}
编辑:我非常肯定(除非我误解了你的问题)我的解决方案就是你正在寻找的。即所有测试运行后的一种拆卸方法。不需要侦听器,JUnit 有此功能。谢谢。
刚刚遇到同样的问题。
我的解决方案:
Runtime.getRuntime().addShutdownHook(new Thread(() -> do_your_global_cleanup())));
您始终可以编写自定义的 TestRunner。但是,在这样做之前,您需要评估是否需要这样做。最好使用@BeforeClass和@AfterClass。我可以指出的另一个例子是,hibernate 允许用户使用“import.sql”进行单元测试。
无需使用套件,只需添加@BeforeClass和@AfterClass为static即可
public class Tests {
@BeforeClass
public static void doYourOneTimeSetup()
{
...
}
@AfterClass
public static void doYourOneTimeTeardown() {
...
}
@Test
public void testYourTestcase()
{
...
}
}