In C#, it is possible to specify parameters for the same unit test method. Example:
[DataTestMethod]
[DataRow(12,3,4)]
[DataRow(12,2,6)]
public void DivideTest(int n, int d, int q)
{
Assert.AreEqual( q, n / d );
}
Is it possible to do the same in Java? I have read Parametrized runner but this solution is not as easy to use.
The Spock Framewok offers Data Driven Testing for Java and Groovy.
The Tests are ( unfortunately? ) written in 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 } }
With JUnit 5, parameterized tests are really more straight and natural to use as with JUnit 4.
In your case, to provide multiple parameters as input, you could use the @CsvSource
annotation.
Here are the required dependencies (maven declaration way) :
<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>
And here is a sample code (with required imports) :
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);
}
}
You cannot achieve this so simple with JUnit
out of the box, but you can use 3rd party 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
}
}
yes, eg. JUnit has parameterized tests
https://github.com/junit-team/junit4/wiki/parameterized-tests
The only drawback is that all test methods in the class will be executed for each parameter (row).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.