Search code examples
scalascalatestspecs2

Scalatest or specs2 with multiple test cases


In TestNg and Java, we can run multiple test cases using DataProvider, and this runs as separate tests, meaning execution of a test isn't stopped on failure. Is there an analogue for ScalaTest or Specs/Specs2?


Solution

  • In both ScalaTest and specs2, it is easy to create test cases at run-time, in order to parameterize them with data. Here's an example with specs2:

       class BasketSpecification extends Specification {
    
         "a basket must contain fruits" >> {
           Seq(apple, banana, orange) foreach { fruit => 
             ("it contains: " + fruit) >> {
               basket must contain(fruit)
             }
           }
         }
       }
    

    Then the output is:

     A basket must contain fruits
     + it contains: apple
     + it contains: banana
     + it contains: orange
    

    Whereas the following specification:

       class BasketSpecification extends Specification {
    
         "a basket must contain fruits" >> {
           Seq(apple, cake, orange) foreach { fruit => 
             ("it contains: " + fruit) >> {
               basket must contain(fruit)
             }
           }
         }
       }
    

    Will print out something like:

     A basket must contain fruits
     + it contains: apple
     x it contains: cake
       'basket' does not contain 'cake'
     + it contains: orange