Search code examples
javawindowseclipsejunitcommand

Run External Command Before JUnit Tests in Eclipse


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.


Solution

  • 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 {
        }
    }