Reputation: 2003
So I am practicing parameterised tests in JUnit. I created this class:
public class Operation {
public Operation() {
}
public int add(int value, int num) {
int ans = value + num;
return ans;
}
public int subtract(int value, int num) {
int ans = value - num;
return ans;
}
}
Nothing special, just some methods to run some tests on.
I have this test class here:
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class OperationTest {
private int value;
private int num;
public OperationTest(int expected, int value, int num) {
this.value = value;
this.num = num;
}
@Parameterized.Parameters
public static Collection primeNumbers() {
return Arrays.asList(new Object[][] {
{ 4, 2, 2 },
{ 66, 6, 60 },
{ 20, 19, 1 },
{ 82, 22, 50 },
{ 103, 23, 80 }
});
}
@Test
public void test() {
Operation o = new Operation();
assertTrue(value == o.add(value, num));
}
}
finally I have a class to run my tests:
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(OperationTest.class);
for(Failure f : result.getFailures()) {
System.out.println(f.toString());
}
System.out.println(result.wasSuccessful());
}
}
When I run this, the output is:
test[0](OperationTest): null
test[1](OperationTest): null
test[2](OperationTest): null
test[3](OperationTest): null
test[4](OperationTest): null
false
I am expecting all of them to be true, given that { 4, 2, 2 } means expecting 4 from 2 and 2 which are given as parameters to the add method in the Operation class...I am guessing that this is probably not the right way to do it...
I would be grateful on your insight.
Upvotes: 1
Views: 5627
Reputation: 68847
How can value == value + number
ever be true, given that value
nor number
is zero (as we can see by looking at your test numbers)? You clearly missed something simple in the logic. I guess you need a third parameter that expresses the expected result, so you can do:
expected == o.add(value, number);
Upvotes: 2
Reputation: 1499860
You're not using expected
anywhere - not even making it part of the state of the class. Your assertion here:
assertTrue(value == o.add(value, num));
... is not asserting what you want it to. It's only going to work when num
is 0. Look at it carefully.
You should have:
// final is optional here, of course - but that's what I'd do, anyway :)
private final int expected;
private final int value;
private final int num;
public OperationTest(int expected, int value, int num) {
this.expected = expected;
this.value = value;
this.num = num;
}
And then:
assertTrue(expected == o.add(value, num));
Or better (much clearer diagnostics):
assertEquals(expected, o.add(value, num));
Upvotes: 2