Search code examples
scalaspecs2

Unit testing a method return with org.specs2


I want to perform unit testing on the return values of a method nested under an object. Example:

package code.learn
import org.specs2.mutable._;
import com.learning.run.CMMDC;

class testing extends Specification {

    val t1 = Map(1 -> 6, 7 -> 12, 9 -> 13);
    "testing the results" in {
        foreach(t1) {
            case (key, value) =>
                CMMDC.compute(key, value) must_== value;
        }
    }

}

Solution

  • There is a foreach method (or foreachWhen if you prefer to use a PartialFunction) in specs2 which tests several values for a given example:

    "testing the results" in {
      foreach(t1) { kv => test.sampleMethod(kv._1) must_== someList(kv._2) }
    }
    
    // or
    "testing the results" in {
      foreachWhen(t1) { case (k, v) => test.sampleMethod(k) must_== someList(v) }
    }