ScalaTest测试名称没有夹具?

时间:2016-04-21 09:36:42

标签: scala scalatest

首先,我看到它和this other post听起来完全像我需要的东西,除了一件事,我不能使用fixture.TestDataFixture因为我无法扩展fixture.FreeSpecLike,我相信那里必须是一些方式来获得看起来更像这样的测试名称(想象的代码不能编译)

class MySpec extends FlatSpecLike with fixture.TestDataFixture {
  "this technique" - {
     "should work" in { 
      assert(testData.name == "this technique should work")
    }
    "should be easy" in { td =>
      assert(testData.name == "this technique should be easy")
    }
  }
}

有什么想法吗?我简直不敢相信这样的事情是不可能的:D

3 个答案:

答案 0 :(得分:1)

虽然你基本上已经解决了这个问题,但这是一个更安全的变体:

private val _currentTestName = new ThreadLocal[String]

override def withFixture(test: NoArgTest) = {
  _currentTestName.set(test.name)
  val outcome = super.withFixture(test)
  _currentTestName.set(null)
  outcome
}

protected def currentTestName: String = {
  val testName = _currentTestName.get()
  assert(testName != null, "currentTestName should only be called in a test")
  testName
}

可替换地,

protected def currentTestName = Option(_currentTestName.get())

答案 1 :(得分:0)

并找到了答案(同事们做了),不确定我喜欢它但是有效:

关于其他测试依赖的特性

class MySpec extends FlatSpecLike {
//... other stuff
    var testName = "UndefinedTestName"
    override def withFixture (test: NoArgTest) :Outcome= {
       testName = test.name
       super.withFixture(test)
   }
}

简单的解决方案,但相当模糊,我也想知道是否有人发现任何问题

答案 2 :(得分:0)

您可以使用FlatSpecLike特征中的方法testNames查找测试名称的序列:

import org.scalatest.FlatSpecLike

class FooSpec extends FlatSpecLike {

  it should "check case one" in {
    println("test some code ...")

    println(testNames.mkString("\n"))
    /*
      prints:
      should check case one
      should check case two
    */
    // ...
    assert(1 == 1)
    println("end.")
  }

  it should "check case two" in {
    println("test some code ...")

    assert(1 == 1)
    println("end.")
  }
}

并找到您需要的每个。希望对您有所帮助。