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 开发者_StackOverflowsome 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.
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
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.
精彩评论