Pass command line arguments to JUnit test case being run programmatically

Nick Vallely picture Nick Vallely · May 21, 2010 · Viewed 48.7k times · Source

I am attempting to run a JUnit Test from a Java Class with:

    JUnitCore core = new JUnitCore();
    core.addListener(new RunListener());
    core.run(classToRun);

Problem is my JUnit test requires a database connection that is currently hardcoded in the JUnit test itself.

What I am looking for is a way to run the JUnit test programmatically(above) but pass a database connection to it that I create in my Java Class that runs the test, and not hardcoded within the JUnit class.

Basically something like

    JUnitCore core = new JUnitCore();
    core.addListener(new RunListener());
    core.addParameters(java.sql.Connection);
    core.run(classToRun);

Then within the classToRun:

@Test
Public void Test1(Connection dbConnection){
    Statement st = dbConnection.createStatement();
    ResultSet rs = st.executeQuery("select total from dual");
    rs.next();
    String myTotal = rs.getString("TOTAL");
    //btw my tests are selenium testcases:)
    selenium.isTextPresent(myTotal);
}

I know about The @Parameters, but it doesn't seem applicable here as it is more for running the same test case multiple times with differing values. I want all of my test cases to share a database connection that I pass in through a configuration file to my java client that then runs those test cases (also passed in through the configuration file).

Is this possible?

P.S. I understand this seems like an odd way of doing things.

Answer

tonio picture tonio · May 21, 2010

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.