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?
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);
}
I would look at JUnit 4's parameterised tests, and generate the array of test data dynamically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With