user93796
user93796

Reputation: 18389

issue with junit test case! avoid code duplication

I am writting jnuit test case for testing API.

my class is as follows

class MyTest extends TestCase{
    List<String>  argList;
    public MyTest(){
     //read argList from File
    }



     testMyTest(){
       //callmy api
         myApi(arg1);
       }

}

Now i want make a seperate testcase for each of the 50 args.Args are read from File. I dont want to write a seperate method for calling myApi with different args.How can i do it? I dont want to write sperate methods like

testMyTest1(){
   //callmy api
     myApi(arg1);
   }

testMyTest1(){
   //callmy api
     myApi(arg2);
   }

Upvotes: 1

Views: 600

Answers (4)

John B
John B

Reputation: 32969

private static final String[] args = new String[] {.....};

@Test
public void myTest(){
   for (int i=0; i<args.length; i++){
      myApi(args[i];
   }
}

The above answers your question I think, however it is not good JUnit practice. It is best that each test method only invokes the method under test one time with one test condition. That way if multiple things are wrong, you get a separate error for each rather than dealing with one at a time. This would suggest the following:

private static final String[] args = new String[] {.....};

private void testMyTest(String arg){
    myApi(arg);
}

@Test
public void myTest0(){
  testMyTest(args[0]);
}
@Test
public void myTest1(){
  testMyTest(args[1]);
}

Probably the best mechanism is to do the first option above but using the ErrorCollector rule to allow for multiple errors to be reported.

Edit I stand corrected, jordao's answer regarding parameterized tests is really the best way to do this.

Upvotes: 1

Sergey Gazaryan
Sergey Gazaryan

Reputation: 1043

You can use a Parameterized tests or Theories (since JUnit 4.4). For more details use

Upvotes: 1

ramsvidor
ramsvidor

Reputation: 1490

Unit testing usually is made with assertions. You don't need to write a method for each argument, but execute different assertions based on your arguments.

One way for doing it would be:

class MyApiTest extends TestCase {
    List<String>  argList;

    public MyApiTest() {}

    public testMyApi() {
        assertTrue(testMyApi(arg1));
        assertFalse(testMyApi(arg2));
        assertNull(testMyApi(arg3));
        assertEquals(testMyApi(arg4), testMyApi(arg5));
    }
}

I'd even prefer using annotations, like

class MyApiTest {
    @Before
    public setUp() {}

    @After
    public tearDOwn() {}

    @Test
    public testMyApi() {
        Assert.assertTrue(testMyApi(arg1));
        Assert.assertFalse(testMyApi(arg2));
        Assert.assertNull(testMyApi(arg3));
        Assert.assertEquals(testMyApi(arg4), testMyApi(arg5));
    }
}

Upvotes: 0

Jord&#227;o
Jord&#227;o

Reputation: 56537

You can use a parameterized test for this.

Upvotes: 2

Related Questions