在Eclipse中执行JUnit测试之前运行外部命令
答
非常模糊的问题。具体来说,你没有提到你如何运行你的JUnit测试。你也提到'文件',一个文件可以包含几个JUnit测试。你想在每个测试之前或者在执行任何测试之前运行外部命令吗?
但更多的话题:
如果您正在使用JUnit 4或更高版本,那么你可以标记与@Before
注释的方法和该方法将你的每一个标签@Test
方法之前执行。或者,使用@BeforeClass
标记静态void方法将导致它在类中的任何@Test
方法运行之前运行。
public class MyTestClass {
@BeforeClass
public static void calledBeforeAnyTestIsRun() {
// Do something
}
@Before
public void calledBeforeEachTest() {
// Do something
}
@Test
public void testAccountCRUD() throws Exception {
}
}
如果您使用的是JUnit版本早于4,那么你就可以覆盖setUp()
和setUpBeforeClass()
方法,以替代@Before
和@BeforeClass
。
public class MyTestClass extends TestCase {
public static void setUpBeforeClass() {
// Do something
}
public void setUp() {
// Do something
}
public void testAccountCRUD() throws Exception {
}
}
答
假设你正在使用JUnit 4.0,你可以做到以下几点:
@Test
public void shouldDoStuff(){
Process p = Runtime.getRuntime().exec("application agrument");
// Run the rest of the unit test...
}
如果你想为每个单元测试运行的外部命令,那么你应该这样做在@Before
设置方法。
谢谢。你的帖子基本上回答了我的问题,虽然我希望有些东西不依赖于语言本身(运行配置等)。 – Petr 2012-02-18 22:45:00
@Petr - 没有问题。 JUnit是一个非常紧凑,定义明确的库(大多数人喜欢它的东西之一)。如果你想定制某种外部配置,那么你必须指定更多的细节 - 例如,你是否在IDE中使用Maven,Ant等来启动测试。 – Perception 2012-02-18 22:48:43
@Petr - nvm我看到你编辑了你的问题。我不相信你可以配置一个外部命令作为JUnit调用的一部分运行。但我概述的其他方法应该工作得很好。 – Perception 2012-02-18 22:52:35