Run External Command Before JUnit Tests in Eclipse

Issue

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

Answered By – Perception

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published