scala - Specs2 - 不应在并发环境中使用单位规范样式

标签 scala testing concurrency specs2

Specs2 在处理验收规范(如果需要,甚至是单元规范)时提升函数式风格。

规范中提到了使用旧样式(可变样式)的风险 Specs2 philosophy并关注潜在的不良副作用:

The important things to know are:

side-effects are only used to build the specification fragments, by mutating a variable they are also used to short-circuit the execution of an example as soon as there is a failure (by throwing an exception). If you build fragments in the body of examples or execute the same specification concurrently, the sky should fall down. "context" management is to be done with case classes or traits (see org.specs2.examples.MutableSpec)

我不知道如何同时运行相同的规范,因为每个规范都与另一个不同(分离的类的实例),即使我们同时运行相同的两次或更多次也是如此。

确实,specFragments(可变变量):

protected[mutable] var specFragments: Fragments = new Fragments()

是在名为FragmentBuilder特征中声明的,而不是在对象(在 scala 中 => 单例)或其他共享对象中声明的。 ., 所以 specFragments 是每个 Specification 实例的局部变量。

那么什么场景可能会危及并发机制?

我真的没有想出一个真实的场景(非愚蠢的)来证明 Specs2 函数式风格的好处。

最佳答案

只有在构建规范时才能看到可变规范的问题,而在执行规范时看不到。在构建可变规范时,很容易产生意想不到的副作用

import org.specs2._

val spec = new mutable.Specification {
  "example" >> ok
}
import spec._

def addTitle {
  // WHOOPS, forgot to remove this line!
  // test, add also an example
  "this is only for testing" >> ok

  "new title".title
}
addTitle

输出是:

new title

+ example
+ this is only for testing

Total for specification new title
Finished in 0 ms
2 examples, 0 failure, 0 error

所以,你是对的,指南中突出显示的句子(“同时执行相同的规范”)是模棱两可的。如果多个线程正在构建相同的规范对象,但如果它们正在运行规范对象则规范本身的构造可能不安全(整个过程在该句子中称为“执行”)。

您的另一个问题是:“函数式风格”有什么好处?从用户的角度来看,主要好处是它是另一种编写规范的风格,其中所有文本都放在第一位,所有代码都放在其他地方。

总而言之,如果你喜欢规范的可变风格,不要害怕它!

关于scala - Specs2 - 不应在并发环境中使用单位规范样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14480850/

相关文章:

scala - 从一个衬垫创建多个新实例

eclipse - 如何为 maven/eclipse/scala 仅使用一个 scala 库

c++ - 快疯了,为什么我的变量在我身上发生变化?

Golang并发写入多个文件

scala - ScalaStyle 报告的自动修复警告

scala - 类中的单例对象与伴侣对象

Selenium RC htmlsuite 错误

testing - TestNG - 如何在套件完成后重新运行失败的测试

ios - 我如何在 GCD 中将一个 block 添加到调度队列的前面?

java - ConcurrentHashMap中Bucket级锁和Segment级锁的区别?