Reputation: 1148
Is it possible to run an external command before running tests in a given JUnit file? I run my tests using the Eclipse's Run command. Using JUnit 4.
Thanks.
Upvotes: 0
Views: 1671
Reputation: 2550
Disclaimer: I'm the author of TestProcesses.
Just in case someone lands here searching for a solution:
It's been a while since this question was asked. Assuming you have migrated to JUnit5 in the meantime and are using (or can use) Spring Test, you could have a look at TestProcesses. It is a JUnit5 extension that manages the lifecycle of applications/programs (processes) needed during testing.
It sounds like that's what you're looking for and it allows you to manage the process' lifecycle declaratively, without a lot of boilerplate in your test classes.
https://github.com/netmikey/testprocesses
Upvotes: 0
Reputation: 80603
Very vague question. Specifically, you didn't mention how you are running your JUnit tests. Also you mentioned 'file', and a file can contain several JUnit tests. Do you want to run the external command before each of those tests, or before any of them are executed?
But more on topic:
If you are using JUnit 4 or greater then you can tag a method with the @Before
annotation and the method will be executed before each of your tagged @Test
methods. Alternatively, tagging a static void method with @BeforeClass
will cause it to be run before any of the @Test
methods in the class are run.
public class MyTestClass {
@BeforeClass
public static void calledBeforeAnyTestIsRun() {
// Do something
}
@Before
public void calledBeforeEachTest() {
// Do something
}
@Test
public void testAccountCRUD() throws Exception {
}
}
If you are using a version of JUnit earlier than 4, then you can override the setUp()
and setUpBeforeClass()
methods as replacements for @Before
and @BeforeClass
.
public class MyTestClass extends TestCase {
public static void setUpBeforeClass() {
// Do something
}
public void setUp() {
// Do something
}
public void testAccountCRUD() throws Exception {
}
}
Upvotes: 2
Reputation: 21419
Assuming you are using JUnit 4.0, you could do the following:
@Test
public void shouldDoStuff(){
Process p = Runtime.getRuntime().exec("application agrument");
// Run the rest of the unit test...
}
If you want to run the external command for every unit test, then you should do it in the @Before
setup method.
Upvotes: 1