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?

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
Adrian Panasiuk
  • 7,249
  • 5
  • 33
  • 54

3 Answers3

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);
}
dfa
  • 114,442
  • 31
  • 189
  • 228
  • 1
    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. – SigmaX Oct 11 '15 at 17:04
2

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

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • Now for the question that is always asked with JUnit 4 parametrised tests - how do you set the test case's names? – Stroboskop Jul 27 '09 at 09:34
1

I think your looking for Parameterized Tests in JUnit 4.

JUnit test with dynamic number of tests

Community
  • 1
  • 1
bruno conde
  • 47,767
  • 15
  • 98
  • 117