12

在 TestNg 和 Java 中,我们可以使用 DataProvider 运行多个测试用例,这作为单独的测试运行,这意味着测试的执行不会因失败而停止。ScalaTest 或 Specs/Specs2 是否有类似物?

4

3 回答 3

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
于 2011-07-24T08:28:34.867 回答
12

这个概念在 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 个测试。我相信这就是你所追求的。

于 2011-07-24T18:53:11.117 回答
0

ScalaTest 提供表驱动的属性检查 使用这个工具,您可以针对不同的输入运行测试:

   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
  }
}
于 2020-01-27T13:34:33.637 回答