ScalaTest共享行为函数提前失败

时间:2015-12-03 13:46:01

标签: scala unit-testing testing scalatest

我正在尝试运行测试by sharing behaviour in traits。当我运行这样的测试时,测试总是在出现故障时提前中止,而不是运行其余的测试。

这是我的测试:

trait TestBehaviour extends ShouldMatchers {
  def failEarly = fail("this fails before the test is run")
  def failEarlyAgain = fail("this also fails before the test is run")
}

class Test extends FlatSpec with TestBehaviour {

  it must behave like failEarly

  it must behave like failEarlyAgain  
}

如果我在Eclipse的ScalaTest IDE中运行它,则不会显示任何测试 - RUN ABORTED文本只显示在控制台中:

*** RUN ABORTED ***
  An exception or error caused a run to abort: this fails before the test is run

所以看起来第一次测试正在提前运行。

我希望看到的是测试运行和失败(使用不同的原因消息)。

2 个答案:

答案 0 :(得分:0)

变化

def failEarly = fail("this fails before the test is run")
def failEarlyAgain = fail("this also fails before the test is run")

def failEarly() = fail("this fails before the test is run")
def failEarlyAgain() = fail("this also fails before the test is run")

在您的版本中,您正在调用已定义的方法(因为它们没有参数列表)。在我的版本中,您传递的是从该方法创建的函数(不调用它)

答案 1 :(得分:0)

似乎模板化测试应该包含一个实际的测试用例;像这样

import org.scalatest.FlatSpec

trait TestTemplate { this: FlatSpec =>
  def failEarly() = {
    it should "fail at the right moment" in {
      fail("this fails once for each test that should behave like me")
    }
  }
}


class MyTest extends FlatSpec with TestTemplate {
  "This Test" should behave like failEarly()
  "Some other test" should behave like failEarly()
}

以上示例似乎对我有用。