It is written based on the stable version junit-quickcheck v0.7 as of February 17, 2018.
"Properties" is a characteristic of code that returns a specific output when a specific input is given. For example, assuming a code that factors into prime factors, there is a feature = "property" that a number that is 2 or more and a list of all the numbers that have been factored into prime factors are multiplied to match. (Example) When n = 36, the result of prime factorization is 2, 2, 3, 3, and when multiplied, it becomes 2 x 2 x 3 x 3 = 36, which matches the original n.
For tests using this property, it is not realistic to test all input values n, so junit-quickcheck can randomly generate input values n and perform the test.
It was inspired by Haskell's Quickcheck.
PrimeFactorsProperties.java
@RunWith(JUnitQuickcheck.class)
public class PrimeFactorsProperties {
// 2 - Integer.MAX_Generate input value n in the range up to VALUE (default 100)
@Property
public void factorsMultiplyToOriginal(@InRange(min = "2", max = "2147483647") BigInteger n) {
//Input value n is greater than 1
assumeThat(n, greaterThan(BigInteger.valueOf(1)));
//Multiply the results of prime factorization
BigInteger product = ONE;
for (BigInteger each : PrimeFactors.of(n))
product = product.multiply(each);
//The original n multiplied by the result of prime factorization match
System.out.println("n = " + n);
assertEquals(n, product);
}
}
n = 529647233
n = 1429992675
n = 1879932678
n = 1507927300
n = 1812653008
n = 393176714
n = 368739357
n = 1728382176
n = 607948744
n = 601709453
n = 1993428603
In the above example, the input value is automatically generated for the BigInteger type. Date, enum, String, etc. are also supported. By defining Generator, you can also use your own class.
In the above example, the range of values generated by @InRange is set.
@When(satisfies = "#_ >= 0 && #_ <= 9") int digit) {
It is also possible to set with OGNL like.
By default, 100 values are generated, but you can change it by setting the trials attribute.
@Property(trials = 250) public void northernHemisphere(
By default, different input data is generated each time a JUnit test is executed, but by giving a seed, the same input data will be generated no matter how many times it is executed.
@Property public void holds(@When(seed = -1L) int i) {
I think property-based testing is a complement to traditional testing. In that sense, it can be used as a means to improve quality.
Recommended Posts