I want to combine two tables: one containing inputs and the other containing expected outputs into a single table that I can run through ScalaTest's TableDrivenProperyChecks
framework. Below is essentially what I'm going for:
import org.scalatest.prop.TableDrivenPropertyChecks._
val inputs = Table(
("a", "b"), // First tuple defines column names
( 1, 2), // Subsequent tuples define the data
( -1, 2),
)
val expectedOutputs = Table(
("addition", "subtraction"), // First tuple defines column names
(3, -1), // Subsequent tuples define the data
(1, -3),
)
forAll(inputs zip expectedOutputs) { (a, b, add, sub) =>
sumFn(a, b) should equal (add)
diffFn(a, b) should equal (sub)
}
I know that conventionally tests define the expected values in the same table as the inputs, but I find that to be confusing especially when tuples get long. This feels more elegant if possible.
I see that the org.scalatest.prop.TableFor2
extends scala.IndexedSeq
, but I can't get it to play nicely with forAll
. Basically the inputs zip expectedOutputs
thing doesn't work.
Using tuples with many elements could be hard to read. It becomes harder in a collection. Table-driven property checks helps you to avoid duplicated code when you need to write the same tests with different values. You could have the expected output in the table, but I don't think it will be easier to read or maintain.
The article Knoldus - Table Driven Testing in Scala have a good example where instead of having the expected output in the table, it write tests that return the same value with different inputs:
In this case, the table just have the name of the case that is being validated and then the input value, which is the
Order
in this case.You can see the same approaach in the gist davidallsopp - PropertyTests.scala:
Each test case have different inputs but all of them expect the same output.
From the example provided in your question
It doesn't make sense to use Table-driven property checks (I think it was just a dummy example to avoid complexity). If your real case is similar to something like that, it could be better to validate the logic of your code using Generator-driven property checks. This type of tests is useful when you need to validate some properties, such as commutative property.
Table-driven and Generator-driven property checks comes from Property-based testing.