【发布时间】: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
}
}
}
请注意,它会创建一个测试,并运行特定测试的所有输入。
是否可以通过forAll 为Table 上的每一行创建测试?是否有其他解决方案? (附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