ScalaTest - 根据输入/预期输出创建动态测试 (forAll)

ScalaTest - Create Dynamic tests based on input / expected output (forAll)

考虑以下 Table

object MyTestsFactory {
  val testCases = Table(
    ("testName", "input", "output"),
    ("test-1", "1", 1),
    ("test-2", "2", 2),
    ("test-3", "3", 3), 
  )
}

和以下测试用例:

class MySpec extends FunSuite {
  test("Test Parsing Function") {
    forAll(MyTestsFactory.testCases) { (testName: String, input: String, output: Int) =>
     input.toInt shouldBe output
    }
  }
}

请注意,它创建了一个测试,并在特定测试上运行所有输入。

是否可以通过 forAllTable 上的每一行创建测试?还有其他解决方案吗? (附C#解决方案)

例如:

class MySpec extends FunSuite {
  test("Test Parsing Function") {
    forAll(MyTestsFactory.testCases) { (testName: String, input: String, output: Int) =>
      test(s"Testing $testName") {
        input.toInt shouldBe output
      }
      input.toIntOption match {
        case Some(value) => value shouldBe output
        case None => fail(s"Parsing error on $testName")
      }
    }
  }
}

不编译

TestRegistrationClosedException was thrown during property evaluation. (ConsentStringSpec.scala:12)
  Message: A test clause may not appear inside another test clause.
  Location: (ConsentStringSpec.scala:13)
  Occurred at table row 0 (zero based, not counting headings), which had values (
    testName = test-1,
    input = 1,
    output = 1
  )

有可能吗?


C# 示例:(在 Scala 中寻找类似的东西)

public class MySpec
    {
        [TestCase( "1", 1, TestName = "test-1")]
        [TestCase("2", 2, TestName = "test-2")]
        [TestCase("3", 3, TestName = "test-3")]

        public void TestingParsing(string input, int output)
        {
           Assert.AreEqual(int.Parse(input), output);
        }
    }

您的代码存在问题,您正在尝试嵌套测试。它不能嵌套。请尝试翻转 testforall 顺序,例如:

class MySpec extends FunSuite with Matchers {
  forAll(MyTestsFactory.testCases) {
    x => {
      test("Test Parsing Function" + x._1) {
        x._2.toInt shouldBe x._3
      }
    }
  }
}

然后你得到 3 个测试: