Search code examples
scalaspecs2

Return type from specs2 helper method


Let's assume I write a helper method, that accepts some test code.

def testWithPrintln(test: => A):A = {
    println("I'm happy and testing")
    test
}

What should be the A type be? What is the right one? I'm browsing the specs2 api and there are numerous similar looking types: AsResult[_], Result, MatchResult[_], I'm confused what to use.


Solution

  • Trying to elaborate on @cmbaxter's answer.

    In specs2 the body of an Example needs to be evaluated as a Result, that is either a Success or Failure or Error or Skipped or Pending. In order to provide enough flexibility, the body of an Example will accept any type T that can be transformed to a Result provided that an instance of AsResult[T] is in (the implicit) scope.

    There are instances of AsResult for various types:

    • Boolean: this makes true being a Success and false being a failure

    • Result itself, just returning the value

    • MatchResult[T]: a MatchResult is the result of a matcher execution. This is the result of expressions such as 1 must beEqualTo(1)

    • org.scalacheck.Prop to execute a ScalaCheck property in an example

    In your example, the test helper will work fine if you implement it like this:

    // if `a: A` is acceptable as the body of an example
    // you can use testWithPrintln(a) in your example
    def testWithPrintln[A : AsResult](a: A): A = {
      println(a)
      a
    } 
    

    Note however that the helper you are looking for might already exist in specs2. You can use the .pp method to "print and pass" any value:

    // has type MatchResult[Int]
    (1 must_== 1).pp
    

    Also you can add more verbose messages to your expectations:

     // will print "this is not correct because 1 is not equal to 2"
     "this is correct" ==> { 1 must_== 2 }
    
     // will print "the number of elements: 1 is not greater than 2
     val n = 1
     n aka "the number of elements" must be_>(2)