tags:

views:

235

answers:

3

Checking function takes two arguments, I want to have a testcase for each element of the cartesian product of the respective domains, but without manually writing all the test cases like in

void check(Integer a, Integer b) { ... }

@Test
public void test_1_2() { check(1, 2); }

...

In python I would go with

class Tests(unittest.TestCase):
    def check(self, i, j):
        self.assertNotEquals(0, i-j)



for i in xrange(1, 4):
    for j in xrange(2, 6):
        def ch(i, j):
            return lambda self: self.check(i, j)
        setattr(Tests, "test_%r_%r" % (i, j), ch(i, j))

How could I do this with Java and JUnit?

+1  A: 

I think your looking for Parameterized Tests in JUnit 4.

http://stackoverflow.com/questions/358802/junit-test-with-dynamic-number-of-tests

bruno conde
+2  A: 

I would look at JUnit 4's parameterised tests, and generate the array of test data dynamically.

Brian Agnew
Now for the question that is always asked with JUnit 4 parametrised tests - how do you set the test case's names?
Stroboskop
+2  A: 

with theories you can write something like:

@RunWith(Theories.class)
public class MyTheoryOnUniverseTest {

    @DataPoint public static int a1 = 1;
    @DataPoint public static int a2 = 2;
    @DataPoint public static int a3 = 3;
    @DataPoint public static int a4 = 4;

    @DataPoint public static int b2 = 2;
    @DataPoint public static int b3 = 3;
    @DataPoint public static int b4 = 4;
    @DataPoint public static int b5 = 5;
    @DataPoint public static int b6 = 6;

    @Theory
    public void checkWith(int a, int b) {
        System.out.format("%d, %d\n", a, b);
    }
}

(tested with JUnit 4.5)

EDIT

Theories also produces nice error messages:

Testcase: checkWith(MyTheoryOnUniverseTest):        Caused an ERROR
checkWith(a1, b2) // <--- test failed, like your test_1_2

so you don't need to name your test in order to easly identify failures.

EDIT2

alternatively you can use DataPoint**s** annotation:

@DataPoints public static int as[] = { 1, 2, 3, 4} ;
@DataPoints public static int bs[] = { 2, 3, 4, 5, 6};

@Theory
public void checkWith(int a, int b) {
    System.out.format("%d, %d\n", a, b);
}
dfa