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?

3 Answers 3

5

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 DataPoints 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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

I agree that Theories is the best tool when you want all combinations—but this answer is buggy. Theories doesn't look at your variable names, so it can't tell the difference between the two sets. What you get is the Cartesian product of [ 1, 2, 3, 4, 2, 3, 4, 5, 6 ] with itself. This is true for both the \@DataPoint and \@DataPoints methods.
2

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

1 Comment

Now for the question that is always asked with JUnit 4 parametrised tests - how do you set the test case's names?
1

I think your looking for Parameterized Tests in JUnit 4.

JUnit test with dynamic number of tests

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.