在Junit 4
参数化测试中,如果我在测试类中有3个测试,并且我想在特定测试中使用不同的参数,我应该怎么做?
让我们说第三次测试可以检查特定异常是否会抛出。所以我只需要将错误的参数传递给那个测试。
@RunWith(Parameterized.class)
public class EvenNumberProcessorTest {
private int num1;
private int num2;
public int EvenNumberProcessorTest(int num1, int num2) {
this.num1 = num1;
this.num2 = num2;
}
@Parameterized.Parameters
public static Collection<Integer[]> numbers() {
return Arrays.asList(new Integer[][] {
{4, 2},
{5, 2}
});
}
@Test
public void testCheckDivision() {
Assert.asserEquals(true, EvenNumberProcessor.checkDivision(num1, num2));
}
@Test(expected = MyException.class)
public void testCheckDivisionFail() {
DivisionProcessor.checkDivision(3, 0);
}
}
public boolean checkDivision(int num1, num2) {
boolean result = false;
try {
if (num1 % num2 == 0) {
result = true;
} else {
result = false;
}
} catch (ArithmeticException e) {
throw new MyException("You can not use 0 to divide");
}
return result;
}
答案 0 :(得分:0)
您可以通过添加另一个参数来传递测试构造函数中的预期输出。我已更新您的代码以反映以下内容:
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 EvenNumberProcessorTest {
private final int num1;
private final int num2;
private final boolean expectFailure;
public EvenNumberProcessorTest(int num1, int num2, boolean expectFailure) {
this.num1 = num1;
this.num2 = num2;
this.expectFailure = expectFailure;
}
@Parameterized.Parameters
public static Collection<Object[]> numbers() {
return Arrays.asList(new Object[][] { { 4, 2, false }, { 5, 0, true } });
}
@Test
public void testCheckDivision() {
try {
boolean result = EvenNumberProcessor.checkDivision(num1, num2);
if (expectFailure) {
junit.framework.Assert.fail("MyException expected but not thrown.");
} else {
junit.framework.Assert.assertEquals(true, result);
}
} catch (Exception ex) {
if (!expectFailure) {
junit.framework.Assert.fail("MyException not expected but thrown.");
}
}
}
}
正如您可能已经猜到的那样,您可以将预期结果(true / false)传递给构造函数。
答案 1 :(得分:0)
@Parameterized
对此有点太重了。尝试更简单的事情。以下示例使用zohhak和assertj
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.googlecode.zohhak.api.TestWith;
import com.googlecode.zohhak.api.runners.ZohhakRunner;
@RunWith(ZohhakRunner.class)
public class MyTest {
@Test(expected=IllegalArgumentException.class)
public void should_throw_exception_on_division_by_zero() {
checkDivision(3, 0);
}
@TestWith({
"4, 2, true",
"5, 2, false"
})
public void should_check_if_divisable(int num1, int num2, boolean isDivisible) {
assertThat(checkDivision(num1, num2)).isEqualTo(isDivisible);
}
public boolean checkDivision(int num1, int num2) {
...
}
}