gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:55:50 26 4
gpt4 key购买 nike

考虑以下:

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);
}
}

enter image description here

最佳答案

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

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

然后你得到 3 个测试:

enter image description here

关于ScalaTest - 根据输入/预期输出创建动态测试 (forAll),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68041007/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com