Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

force sample to return Some(Value) instead of None #224

Closed
nykolaslima opened this issue Mar 16, 2016 · 3 comments
Closed

force sample to return Some(Value) instead of None #224

nykolaslima opened this issue Mar 16, 2016 · 3 comments

Comments

@nykolaslima
Copy link

I'm using Scalacheck to define objects that will be used in my unit tests.

val listingGen = for {
    id <- posNum[Long]
    name <- alphaStr
} yield Listing(id, name)

//I want that listingGen always return me a Listing
listingGen.sample.get

the listingGen.sample could return None. How can I force scalacheck to return me Some(Listing)?

@rickynils
Copy link
Contributor

In the general case, you can't. ScalaCheck generators can fail, for instance if you're adding a filter (listingGen.suchThat(...)), and that failure is modeled with the Option type. However, if you're sure that your generator never will fail, you can simply call Option.get like you do in your example above. Or you can use Option.getOrElse to replace None with a default value.

If you know that your generator might fail, but very seldomly, you can use Gen.retryUntil(_ => true). This will simply re-run a generator if it fails. You should be careful with this, since you might end up in a non-terminating loop, though.

@SethTisue
Copy link
Member

sounds like this should just be closed?

@non
Copy link
Contributor

non commented Sep 3, 2019

👍

@non non closed this as completed Sep 3, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants