在TestNg和Java中,我们可以使用DataProvider运行多个测试用例,这可以作为单独的测试运行,这意味着测试的执行不会在失败时停止。是否有ScalaTest或Specs / Specs2的模拟?
答案 0 :(得分:25)
在ScalaTest和specs2中,很容易在运行时创建测试用例,以便使用数据对它们进行参数化。这是specs2的一个例子:
class BasketSpecification extends Specification {
"a basket must contain fruits" >> {
Seq(apple, banana, orange) foreach { fruit =>
("it contains: " + fruit) >> {
basket must contain(fruit)
}
}
}
}
然后输出是:
A basket must contain fruits
+ it contains: apple
+ it contains: banana
+ it contains: orange
以下规范:
class BasketSpecification extends Specification {
"a basket must contain fruits" >> {
Seq(apple, cake, orange) foreach { fruit =>
("it contains: " + fruit) >> {
basket must contain(fruit)
}
}
}
}
将打印出类似的内容:
A basket must contain fruits
+ it contains: apple
x it contains: cake
'basket' does not contain 'cake'
+ it contains: orange
答案 1 :(得分:10)
这个概念在ScalaTest中被称为“共享测试”,因为相同的测试代码被多个灯具“共享”,其中“灯具”是TestNG的DataProvider方法中的“数据”。对于ScalaTest中的每个样式特征,有一种方法可以将测试表示为函数。以下是WordSpec的示例:
http://www.scalatest.org/scaladoc-1.6.1/#org.scalatest.WordSpec@SharedTests
您也可以使用for循环为不同的数据点注册相同的测试代码。这是在一个电子邮件讨论中出现的:
http://groups.google.com/group/scalatest-users/browse_thread/thread/7337628407b48064#
在这种情况下,for循环代码看起来像:
for (browser <- List("IE", "Chrome", "Firefox")) {
test(browser + ": test one") { driver =>
info("Testing using " + driver)
}
test(browser + ": test two") { driver =>
info("Testing using " + driver)
}
test(browser + ": test three") { driver =>
info("Testing using " + driver)
}
test(browser + ": test four") { driver =>
info("Testing using " + driver)
}
test(browser + ": test five") { driver =>
info("Testing using " + driver)
}
}
}
这实际上记录了15个测试,每个浏览器驱动程序有5个测试。我相信这就是你所追求的。
答案 2 :(得分:0)
ScalaTest提供Table-driven property checks 使用此工具,您可以针对不同的输入进行测试:
import org.scalatest.prop.TableDrivenPropertyChecks._
val fractions =
Table(
("n", "d"), // First tuple defines column names
( 1, 2), // Subsequent tuples define the data
( -1, 2),
( 1, -2),
( -1, -2),
( 3, 1),
( -3, 1),
( -3, 0),
( 3, -1),
( 3, Integer.MIN_VALUE),
(Integer.MIN_VALUE, 3),
( -3, -1)
)
/*------------------------------------------------*/
import org.scalatest.matchers.ShouldMatchers._
forAll (fractions) { (n: Int, d: Int) =>
whenever (d != 0 && d != Integer.MIN_VALUE
&& n != Integer.MIN_VALUE) {
val f = new Fraction(n, d)
if (n < 0 && d < 0 || n > 0 && d > 0)
f.numer should be > 0
else if (n != 0)
f.numer should be < 0
else
f.numer should be === 0
f.denom should be > 0
}
}