Pass command line arguments to JUnit test case being run programmatically

You can use java system properties to achieve this.

Simply pass what you need with -Dconnectionstring=foobar in the junit command line, or use the java api for system properties to set this programmatically, with System.setProperty(String name, String value), and System.getProperty(String name).

In your tests, you can use the @Before or @BeforeClass to set up common objects based on this property, pending on whether you want to run the setup once for each test (in which case you can use class members) or once for each suite (and then use static members).

You can even factorize this behavior by using an abstract class which all your test cases extends.

Leave a Comment