ScalaTest test name without fixture?

為{幸葍}努か 提交于 2019-12-10 15:54:38

问题


First off, I saw it and this other post sounds exactly like what I need except for one thing, I can't use fixture.TestDataFixture because I can't extend fixture.FreeSpecLike, and I am sure that there must be some way to get the test name in a way that looks more like this (imagined code that doesn't compile)

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")
    }
  }
}

Any ideas? I just can't believe something like this is not possible :D


回答1:


While you already came to basically this solution, here is a safer variation:

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
}

Alternately,

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



回答2:


And found an answer(well a collegue did), not sure I like it but works:

on the trait that other tests depend on

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

simple solution but rather obscure, also I wonder if anyone sees any problems with it




回答3:


You can find sequence of test names using method testNames in FlatSpecLike trait:

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.")
  }
}

and find each you needed. Hope it helps.



来源:https://stackoverflow.com/questions/36765577/scalatest-test-name-without-fixture

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!