0
votes

I wanted to know if there's any way to add test suites dynamically in junit 4.

For example I have a TestClassA as mentioned below having test case "test1"

class TestClassA 
{
    @Test
    public void test1()
    {
        createTestClassDynamically(); // this creates a test class having
                        // setUp(), tearDown() methods and one test case .
    }
}

Test case test1 has a method createTestClassDynamically() that dynamically creates a new test class (lets say TestClassB) having setUp(), tearDown() methods and one test case (lets say test2()).

I want to run the test1 and then when TestClassB is dynamically generated I want test case "test2" also to be executed.

I know this is quite complicated and not the best thing to do but in my framework I need to do it to generate large number of test classes dynamically rather than having them physically in the package. Can anyone please provide any help/suggestions?

1
Why do you need to generate the java dynamically?Matthew Farwell
I need to generated 100s of classes from a a class template and then add these classes to currently running suite so that the test case inside these gets executed. Earlier in junit 3.8 we used to add the tests to global suite variable using suite.addTestSuite(dynamicClassHere); But in junit 4.10 when I'm trying that way I'm getting ConcurrentModificationException.user85

1 Answers

0
votes

I have solved this is my framework using the Parameterized feature of Junit 4 which helps to execute same test case with different parameters.
Below mentioned is the sample code on how I acheived it, thought to post it if it helps anyone.
Also, if someone has a better solution, feel free to post it.

class TestClassA 
{

  private TestClassB classBObj;

  public TestClassA(TestClassB obj) {
   classBObj= obj;
  }

@Test
public void test1()
{
// createTestClassDynamically(); // remove this method as Parameterized 
                // feature will take care of dynamic test execution.
}

@Test
public void test2()
{
 // Test case from Test class B using TestClassB object (classBObj)

}

public static Collection<Object[]> getParameters() {
  Collection<Object[]> parameteres = new ArrayList<Object[]>();

  Object[] obj1 = new Object[]{new TestClassB()};
  Object[] obj2 = new Object[]{new TestClassB()};

  parameteres.add(obj1);
  parameteres.add(obj2);

  // ....... add more test data this way or create a loop

  return parameteres;
   }
}