[英]Java unit testing with parameter
在C#中,可以为同一单元测试方法指定参数。 例:
[DataTestMethod]
[DataRow(12,3,4)]
[DataRow(12,2,6)]
public void DivideTest(int n, int d, int q)
{
Assert.AreEqual( q, n / d );
}
是否可以在Java中执行相同的操作? 我已经阅读了Parametrized赛跑者,但是这种解决方案并不容易使用。
Spock Framewok提供了Java和Groovy的数据驱动测试 。
测试( 不幸的是? )是用Groovy编写的:
class MathSpec extends Specification { def "maximum of two numbers"() { expect: Math.max(a, b) == c where: a | b || c 1 | 3 || 3 7 | 4 || 7 0 | 0 || 0 } }
与JUnit 4相比,使用JUnit 5进行参数化测试实际上更加直接和自然。
对于您的情况,要提供多个参数作为输入,可以使用@CsvSource
批注。
这是必需的依赖项(Maven声明方式):
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.0.0-M4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<version>5.0.0-M4</version>
<scope>test</scope>
</dependency>
这是一个示例代码(带有必需的导入):
import org.junit.Assert;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class YourTestClass{
@ParameterizedTest
@CsvSource({ "12,3,4", "12,2,6" })
public void divideTest(int n, int d, int q) {
Assert.assertEquals(q, n / d);
}
}
开箱即用JUnit
不能实现如此简单的功能,但是您可以使用第三方JUnitParams :
@RunWith(JUnitParamsRunner.class)
public class PersonTest {
@Test
@Parameters({"17, false",
"22, true" })
public void personIsAdult(int age, boolean valid) throws Exception {
assertThat(new Person(age).isAdult(), is(valid));
}
@Test
public void lookNoParams() {
etc
}
}
是的,例如 JUnit具有参数化测试
https://github.com/junit-team/junit4/wiki/parameterized-tests
唯一的缺点是将对每个参数(行)执行该类中的所有测试方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.