Java jUnit:在任何测试类之前运行的测试套件代码

我有一个测试套件类:

@RunWith(Suite.class) @Suite.SuiteClasses({ GameMasterTest.class, PlayerTest.class, }) public class BananaTestSuite { 

在包含实际测试的任何类之前,我需要使用什么注释来在此类中运行函数? 现在,我正在这样做,它可以工作,但它不是那么可读:

 static { try { submitPeelAction = new Player(new GameMaster(1)).getClass().getDeclaredMethod("submitPeelAction"); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } submitPeelAction.setAccessible(true); } 

我试过@BeforeClass但它没有用。

创建一个包含使用@BeforeClass注释的方法的超级测试类。 扩展此类中的所有测试类,例如,

 @Ignore public class BaseTest { @BeforeClass public static void setUpBaseClass() { //Do the necessary setup here } } 

此方法将在子类中的任何@BeforeClass注释方法之前运行: Source 。 确保未在任何子类中使用此方法名称以防止出现阴影。

如果您只需要运行一次(例如,如果要为所有要使用的测试创建/初始化大型资源),请在超类中设置一个标志以检查方法是否运行。

此设计还将确保如果您更改测试运行器,则无需更改任何其他内容。

使用@Before用于setUp()和@After用于tearDown方法。

编辑:经过一些测试后我发现@Before@After不适用于Test Suite。 在您的情况下,您应该使用@BeforeClass和静态方法来封装您的初始化代码。

 @RunWith(Suite.class) @SuiteClasses( { ContactTest.class }) public class AllTests { @BeforeClass public static void init() { System.out.println("Before all"); } } 

首先:如果您使用最新的JUnit,即4.7或更高版本,您也可以使用规则完成此操作。 有关起点,请参阅http://www.infoq.com/news/2009/07/junit-4.7-rules 。

据我所知,套件类中的静态块是一个很好的解决方案。

缺点是它只会在您运行整个套装时调用,而不是单独的测试或测试类。 因此,另一种方法是从所有类中的@BeforeClass方法调用套件类中的相同静态方法。

使用@BeforeClass注释方法,使其在该类中运行所有测试之前运行。 使用@Before注释方法,使其在该类中的每个测试之前运行。

回覆。 你的评论@BeforeClass工作正常。 你在该方法中抛出exception吗?

尝试使用@before并创建一个方法来实例化所有对象,如果你需要在结束后使用@After清除一些东西

像这样的东西:

 @Before public void instanceMeasureList() { /* all what you need to execute before starting your tests */ } @Test public void testRequest() { fail("Not yet implemented"); } @Test public void testEpochDate() { fail("Not yet implemented"); } @After public void deleteOutputFile() { fail("Not yet implemented"); }