Reputation: 3378
I have read in the ScalaCheck user guide that it's a tool for testing Scala and Java programs.
I wonder, is it just marketing, or testing Java-only codebase with it would be a reasonable idea? And if so, what's the best way to integrate it with the Java project?
Upvotes: 8
Views: 2560
Reputation: 51683
Actually you can write ScalaCheck tests in pure Java although you'll have to resolve Scala implicits manually.
For example the code in Scala
import org.scalacheck.Properties
import org.scalacheck.Prop.forAll
object CommutativityTest extends Properties("Commutativity Test") {
property("commutativity") = forAll { (a: Int, b: Int) =>
a + b == b + a
}
}
with build.sbt
scalaVersion := "2.12.3"
libraryDependencies += "org.scalacheck" %% "scalacheck" % "1.13.5" % Test
can be translated to Java as
import org.scalacheck.*;
import org.scalacheck.util.Pretty;
import scala.math.Numeric;
public class CommutativityTest$ extends Properties {
public static final CommutativityTest$ MODULE$ = new CommutativityTest$();
public CommutativityTest$() {
super("Commutativity Test");
Arbitrary arbInt = Arbitrary.arbInt();
Shrink shrinkInt = Shrink.shrinkIntegral(Numeric.IntIsIntegral$.MODULE$);
Prop prop = Prop.forAll(
(Integer a, Integer b) -> a + b == b + a,
Prop::propBoolean,
arbInt,
shrinkInt,
Pretty::prettyAny,
arbInt,
shrinkInt,
Pretty::prettyAny
);
property().update("commutativity", () -> prop);
}
}
and
public class Runner {
public static void main(String[] args) {
CommutativityTest$.MODULE$.main(args);
}
}
with pom.xml
<project...
<dependencies>
<dependency>
<groupId>org.scalacheck</groupId>
<artifactId>scalacheck_2.12</artifactId>
<version>1.13.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.scala-lang.modules</groupId>
<artifactId>scala-java8-compat_2.12</artifactId>
<version>0.8.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
The output:
+ Commutativity Test.commutativity: OK, passed 100 tests.
Upvotes: 2
Reputation: 16265
No, it's not just marketing. Funcional Java (http://functionaljava.org/) is tested with ScalaCheck. Some test cases in the FJ sources: https://github.com/functionaljava/functionaljava/blob/724081f0f87f34b2f4c26b8b748877955180ecaa/props-core-scalacheck/src/test/scala/fj/data/CheckList.scala
I'm not sure what's the best way to integrate ScalaCheck into an existing java project but I guess you could borrow some ideas from how it's done in FJ.
Upvotes: 8