Parametrized testing in scala with MUnit, is it possible?

175 views Asked by At

I am trying to figure out if I can create parametrized tests with MUnit or ScalaCheck. ScalaCheck allows me to create property-based tests. However, the only way I have seen that I can create parametrized tests is with ScalaTest. See here: https://www.scalatest.org/user_guide/table_driven_property_checks.

My test suite already depends on MUnit and ScalaCheck, I would not like to add another library on the mix. Otherwise, I think I am going to get rid of MUnit and replace it with ScalaTest.

1

There are 1 answers

5
Gastón Schabas On

It doesn't seem that MUnit offers something like Table-driven property checks. MUnit has integration with scalacheck, but doesn't add anything similar to what you are looking for.

One possible approach could be something like

import munit.FunSuite

class MUnitTest extends FunSuite {

  val table = List(
    (1,1),
    (2,-2),
    (3,3)
  )

  for(t <- table) test(s"${t._1} should be equals ${t._2}") {
    assertEquals(t._1, t._2)
  }

}

the output will be

MUnitTest:
  + 1 should be equals 1 0.05s
==> X MUnitTest.2 should be equals -2  0.033s munit.ComparisonFailException: MUnitTest.scala:15
14:  yield test(s"${t._1} should be equals ${t._2}") {
15:    assertEquals(t._1, t._2)
16:  }
values are not the same
=> Obtained
2
=> Diff (- obtained, + expected)
-2
+-2
    at munit.FunSuite.assertEquals(FunSuite.scala:11)
    at MUnitTest.$anonfun$new$2(MUnitTest.scala:15)
  + 3 should be equals 3 0.0s
[error] Failed: Total 3, Failed 1, Errors 0, Passed 2
[error] Failed tests:
[error]     MUnitTest

It's not exactly the same. Doing this, instead of having just one use case where the error message of a failed test shows what is the set of values that make the test fails, you will be generating new test cases per each group of values you have in the list. Using the Table class also lets put a label for each value, which something useful when you get an error. Even title of the test could be wrong.

This could be improved with some helper, but I think that would be trying to recreate what is offered by ScalaTest