Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Scalatest have any support for assumptions?

As per the title, I'm wondering if it's possible to provide "assumptions" to Scalatest when defining a particular test case. Assumptions in this context would be preconditions for a test, such that if the assumption evaluated to false, the test would be skipped rather than executed (and handled accordingly by the runners).

In this particular case, I'm thinking about dependencies between tests - so there might be a basic test that validates whether a method returns anything at all, followed by later tests that drill into the specifics of the response. If the former test fails, I'd rather have the latter test marked as "not runnable" in some way, rather than have them fail as well.

That said I can imagine using this in future to define some unconnected preconditions (such as the hard drive must have at least 20MB of space free), so if there's a general way of skippin a test at runtime (as opposed to using ignore or pending) I'd prefer to hear that.

Specialised syntax is welcome, though if I have to manually throw a certain kind of exception that's OK too.

like image 628
Andrzej Doyle Avatar asked Aug 17 '11 16:08

Andrzej Doyle


2 Answers

ScalaTest 2.0 (I think) added support for assumptions:

Trait Assertions also provides methods that allow you to cancel a test. You would cancel a test if a resource required by the test was unavailable. For example, if a test requires an external database to be online, and it isn't, the test could be canceled to indicate it was unable to run because of the missing database. Such a test assumes a database is available, and you can use the assume method to indicate this at the beginning of the test, like this:

assume(database.isAvailable)

http://www.scalatest.org/user_guide/using_assertions

like image 77
MHarris Avatar answered Nov 09 '22 20:11

MHarris


Scalacheck, which is often used in combination with scalatest, can do it:

import org.scalacheck._

object XSpecifictaion extends Properties ("X") { 

    property ("sample (a - b)") = Prop.forAll { (a: Int, b: Int) =>  
      (a < b || (a - b >= 0)) }
}

! (a < b) is your assumption, and (a - b >= 0) the real test; you perform the latter only, if the assumption is true, so you negate your assumption and combine it with a shortcut-OR.

like image 28
user unknown Avatar answered Nov 09 '22 18:11

user unknown