我在谷歌上搜索了 JUnit 测试用例,它提出了一些看起来实现起来要复杂得多的东西——你必须创建一个扩展测试用例的新类,然后调用它:
public class MathTest extends TestCase {
protected double fValue1;
protected double fValue2;
protected void setUp() {
fValue1= 2.0;
fValue2= 3.0;
}
}
public void testAdd() {
double result= fValue1 + fValue2;
assertTrue(result == 5.0);
}
但我想要的是一些非常简单的东西,比如 NUnit 测试用例
[TestCase(1,2)]
[TestCase(3,4)]
public void testAdd(int fValue1, int fValue2)
{
double result= fValue1 + fValue2;
assertIsTrue(result == 5.0);
}
有没有办法在 JUnit 中做到这一点?
最佳答案
2017 更新: JUnit 5 将通过 junit-jupiter-params
包含参数化测试延期。来自 documentation 的一些示例:
原始类型的单个参数 ( @ValueSource
):
@ParameterizedTest
@ValueSource(strings = { "Hello", "World" })
void testWithStringParameter(String argument) {
assertNotNull(argument);
}
逗号分隔值 (
@CsvSource
) 允许指定多个参数,类似于下面的 JUnitParams:@ParameterizedTest
@CsvSource({ "foo, 1", "bar, 2", "'baz, qux', 3" })
void testWithCsvSource(String first, int second) {
assertNotNull(first);
assertNotEquals(0, second);
}
其他源注释包括
@EnumSource
, @MethodSource
, @ArgumentsSource
和 @CsvFileSource
,见 documentation详情。原答案:
JUnitParams ( https://github.com/Pragmatists/JUnitParams ) 似乎是一个不错的选择。它允许您将测试参数指定为字符串,如下所示:
@RunWith(JUnitParamsRunner.class)
public class MyTestSuite {
@Test
@Parameters({"1,2", "3,4"})
public testAdd(int fValue1, int fValue2) {
...
}
}
您还可以通过单独的方法、类或文件指定参数,请参阅 JUnitParamsRunner api docs详情。
关于unit-testing - 是否有与 NUnit 的 testcase 属性等效的 JUnit?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4554128/