Search code examples
scalascalatest

Can you dynamically generate Test names for ScalaTest from input data?


I have a number of test data sets that run through the same ScalaTest unit tests. I'd love if each test data set was it's own set of named tests so if one data set fails one of the tests i know exactly which one it was rather than going to a single test and looking on what file it failed. I just can't seem to find a way for the test name to be generated at runtime. I've looked at property and table based testing and currently am using should behave like to share fixtures, but none of these seem to do what I want.

Have I not uncovered the right testing approach in ScalaTest or is this not possible?


Solution

  • You could write a base test class, and extend it for each data set. Something like this:

    case class Person(name: String, age: Int)
    
    abstract class MyTestBase extends WordSpec with Matchers {
    
      def name: String
      def dataSet: List[Person]
    
      s"Data set $name" should {
        "have no zero-length names" in {
          dataSet.foreach { s => s.name should not be empty }
        }
      }
    }
    
    class TheTest extends MyTestBase {
      override lazy val name = "Family" // note lazy, otherwise initialization fails
      override val dataSet = List(Person("Mom", 53), Person("Dad", 50))
    }
    

    Which produces output like this:

    TheTests:
    Data set Family
    - should have no zero-length names