【问题标题】:Specs2 unit specification referencingSpecs2 单位规格参考
【发布时间】:2019-11-27 08:01:01
【问题描述】:

我有以下规格:

import org.specs2.mutable.{After, Specification}
import org.specs2.specification.Scope
import org.specs2.specification.core.{Fragment, Fragments}

class TestRefSpec extends Specification {

  "My Spec" >> new iii {
    xxx(i)
  }

  def xxx(i: Int) = {
    def e1 = {
      println(s"** $i > 0")
      i must be_>(0)
    }
    def e2 = {
      println(s"** $i < 100")
      i must be_<(100)
    }

    "i should be > 0" >> { e1 } 
    "and < 100" >> { e2 }
  }

}

trait iii extends Scope with After {
  val i = 142

  def after = println("finalising")
}

这个想法是有一个规范来测试某物的行为,然后有一个目标由测试行为的范围所代表。 理想情况下,这些行为将位于一个单独的特征中。 唉,当我运行它时,我得到的输出如下:

[info] TestRefSpec
[info] + My Spec
[info] Total for specification TestRefSpec
[info] Finished in 560 ms
[info] 1 example, 0 failure, 0 error

这意味着测试并没有真正运行。

有谁知道我如何真正实现我的目标?

提前致谢!

【问题讨论】:

    标签: scala specs2


    【解决方案1】:

    我认为问题在于您将 xxx(i) 方法调用包装在 new iii {} 中。

    这是行不通的,因为花括号内的代码是在扩展iii 的新匿名类的构造函数中执行的,整个表达式的结果是iii 的子类型,而不是Fragments,因此示例的内部结构,您从xxx() 方法内部构造并返回,无法使其进入specs2 &gt;&gt; 运算符。 通常只有个别的例子 - 前面有 specs2 in 运算符被包装在一个范围内。

    这将起作用:

    class TestRefSpec extends Specification {
    
      "My Spec" >> {
        xxx(42)
      }
    
      def xxx(i: Int) = {
        def e1 = {
          println(s"** $i > 0")
          i must be_>(0)
        }
        def e2 = {
          println(s"** $i < 100")
          i must be_<(100)
        }
    
        "i should be > 0" in new iii { e1 }
        "and < 100" in new iii { e2 }
      }
    
    }
    

    【讨论】:

    • 我明白了。然而,这种方法将范围与示例紧密结合在一起。有什么办法可以将它们分开吗?我在这里使用 Scope 的原因是,我要测试的东西的其中一个实现需要在最后进行清理。
    • 我想我现在已经明白了。我会让 xxx 接受我正在测试的事物的实例,并且 AfterAll 以接近整个测试。非常感谢您解释我最初的方法有什么问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-02
    • 1970-01-01
    • 2011-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多