views:

56

answers:

1

I am creating a custom test runner for JUnit test cases using JUnitCore's run(junit.framework.Test test) and passing in ClassName.suite(). My tests run, however the results returned are null. It seems that objects are not being initialized in the setUp() method cause setUp() apparently is never called as it should, even with the @Before annotation. The tests are successful if I instantiate each object required within each test method. This approach however is tedious and defeats the purpose of having a test class. Is this behavior normal? Are there better test runners out there for JUnit that reflect the same behavior as the test runner in Eclipse? Thanks.

Here is the code for the runner:

public class TestRunner
{
    Result res = new Result();
    String results = new String();
    JUnitCore runner = new JUnitCore();

    protected TestRunner()
    {
    }

    public String runReport(Test input)
    {
        System.out.println(input.toString());
        res = runner.run(input);
        String testClass = "Class: ";
        String testFailCt = "Failure Count: ";
        String testFalures = "Failures: ";
        String testRunCt = "Runs: ";
        String testRunTm = "Run Time: ";
        String testSuccess = "Success: ";
        String newln = "\n";
        results += testClass + input.getClass() + newln;
        results += testFailCt + res.getFailureCount() + newln;
        results += testFalures + newln;
        List<Failure> failures = res.getFailures();
        int i = 0;
        for (Failure x: failures)
        {
            i++;
            results += i +": " + x + newln;
        }
        results += testRunCt + res.getRunCount() + newln;
        results += testRunTm + res.getRunTime() + newln;
        results += testSuccess + res.wasSuccessful() + newln;
        return results;
    }
}

Here is how the runReport() method is being called from another class:

runner.runReport(TestClassName.suite());

What should I pass into run() so that setUp() will be implicitly called before each test? I know passing in the suite will not do so. Therefore, I just altered my test cases so that all necessary objects are instantiated within each test.

A: 

... setUp() apparently is never called as it should, even with the @Before annotation.

JUnit version 4 has annotation support - I think junit.framework indicates that you are using Version 3. If you are running JUnit 4 tests using a JUnit 3 TestRunner, you might find these articles of interest:

JUnit Test Runner that creates tests just before running them

JUnit FAQ - see "Writing Tests" para. 3.

An early look at JUnit 4

Good luck!

richj
Thanks for the answer and for the links, I will definitely look into it.
Vapen