Skip to content

Instantly share code, notes, and snippets.

@lukaspustina
Created July 22, 2014 09:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lukaspustina/e861b9d74d962752df51 to your computer and use it in GitHub Desktop.
Save lukaspustina/e861b9d74d962752df51 to your computer and use it in GitHub Desktop.
import org.scalacheck._
import org.scalatest._
import org.scalatest.prop.GeneratorDrivenPropertyChecks
class SubsetGenerator(set: String*) {
protected val subsets = set.toSet.subsets.toSeq
val arbitrarySubsetGen: Gen[Set[String]] = for {
subset <- Gen.oneOf(subsets)
} yield subset
implicit val arbitrarySubset: Arbitrary[Set[String]] = Arbitrary(arbitrarySubsetGen)
}
class SubsetSpecification extends FeatureSpec with GivenWhenThen with ShouldMatchers with
GeneratorDrivenPropertyChecks {
feature("Subsets") {
scenario("The size of a subset should be between 0 and 3") {
val sg = new SubsetGenerator("One", "Two", "Three")
import sg._
forAll("subset") { (subset: Set[String]) =>
whenever(subset.size < 3) {
Given("the subset " + subset)
And("the size should be < 3")
subset.size should be < 3
}
}
}
}
}
@rickynils
Copy link

Instead of writing your own generator, you can use ScalaCheck's Gen.someOf that generates a subset of a list of elements:

...
  feature("Subsets") {

    scenario("The size of a subset should be between 0 and 3") {
      val sg = Gen.someOf("One", "Two", "Three")

      forAll(sg) { (subset: Seq[String]) =>
        whenever(subset.size < 3) {
          Given("the subset " + subset)

          And("the size should be < 3")
          subset.size should be < 3
        }
      }
    }
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment