【问题标题】:ScalaTest - Create Dynamic tests based on input / expected output (forAll)ScalaTest - 根据输入/预期输出创建动态测试 (forAll)
【发布时间】:2021-09-03 12:52:24
【问题描述】:

考虑以下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);
        }
    }

【问题讨论】:

  • 为什么要对每个案例进行测试?
  • 为了清楚地查看哪个测试通过以及哪个测试失败,我想为带有输入/预期输出的测试用例创建工厂,并使用通用代码进行检查。 c#上有类似的东西,我重新编辑帖子
  • Uhm AFAIK forAll 应该会生成有关哪个测试失败的详细错误消息。无论如何,你应该清楚你想要的只是一个好的错误信息。
  • 可能forAll 不是正确的解决方案,请查看c# 解决方案

标签: scala unit-testing scalatest


【解决方案1】:

你的代码的问题是你试图嵌套你的测试。它不能嵌套。请尝试翻转testforall 的顺序,例如:

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

然后你得到 3 个测试:

【讨论】:

  • 工作得很好,IDE 中有一个错误,您必须运行整个类/规范才能使其运行,例如运行测试层次结构中的特定测试将无法运行,例如:@987654326 @ 将无法通过单击 first hirearchy 的运行测试来工作 - 感谢 Tomer!
猜你喜欢
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-26
  • 2015-02-11
  • 2019-09-29
  • 1970-01-01
相关资源
最近更新 更多