charu
charu

Reputation: 21

How to create a TestSuite with parameterized spring Junit tests

I am trying to bundle my tests in a TestSuite which will pick up files from a directory and run each one after loading spring context.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/META-INF/spring/context-test.xml"})
public class MyTestCase extends TestCase{

    private String fileName;

    public MyTestCase(String fileName){
        this.fileName = fileName;
    }

    @Resource private Processor processor;

    @Before
public void setup(){
    ...
    }

    @Test
    public void test(){
    Read file and run test..
    ...
    }

}

If I do this, it doesn't recognize spring annotations

public class MyTestSuite extends TestCase{

    public static Test suite(){
        TestSuite suite = new TestSuite();
        suite.addTest(new MyTestCase("file1"));
        suite.addTest(new MyTestCase("file2"));
        return suite;
    }
}

I looked it up and found: Spring 3+ How to create a TestSuite when JUnit is not recognizing it , which suggests that I should use JUnit4TestAdapter. Problem with JUnitTestAdapter is that it doesn't allow me to pass in parameters and also would not take MyTestSuite.suite(). I can only do something like:

public class MyTestSuite{

    public static Test suite(){

        return new JUnit4TestAdapter(MyTestCase.class);
    }
}

Your response is highly appreciated.

Thanks

Upvotes: 1

Views: 1378

Answers (2)

Jan Goyvaerts
Jan Goyvaerts

Reputation: 3033

Recently found this solution. In my opinion slightly better since it doesn't rely deprecated code.

Upvotes: 0

charu
charu

Reputation: 21

I had to use deprecated AbstractSingleSpringContextTests to achieve this. AbstractSingleSpringContextTests is from the times when TestContext framework was not available.

public class MyTestCase extends AbstractSingleSpringContextTests {

    private String fileName;

    public MyTestCase(String fileName){
        this.fileName = fileName;
    }

    @Resource private Processor processor;

    @Override
    protected void onSetUp(){

         initialization code...

    }

    @Override
    protected String getConfigPath(){
         return "config/File/Path";
    }

    @Test
    public void test(){
    Read file and run test..
    ...
    }

}


public class MyTestSuite extends TestCase{

    public static Test suite(){
        TestSuite suite = new TestSuite();
        suite.addTest(new MyTestCase("file1"));
        suite.addTest(new MyTestCase("file2"));
        return suite;
    }
}

Its not the best solution, but it works. Please post if you have a better idea.

Upvotes: 1

Related Questions