Access ScalaTest test name from inside test?

后端 未结 3 1220
伪装坚强ぢ
伪装坚强ぢ 2021-02-13 23:30

Is it possible to access the name of the currently executing test, from within a ScalaTest test? (And how would I do it?)

Background:

I\'m testi

3条回答
  •  长情又很酷
    2021-02-14 00:01

    Here's a solution. Extend this class instead of FreeSpec. License: CC0.

    Edit: This doesn't work with concurrent tests though.

    (The difference between this approach and the other answer, is that 1) here there's a currentTestName field, and in the other answer the test name is passed to the test body, and 2) this test name includes all test branch names concatenated + the actual test name, whereas the other answer's test name is exactly the test name (without test branch names).)

    (Ooops, you'd need to use getOrElse ... instead of my lovely getOrDie.)

    /**
     * Adds a field `currentTestName` that you can use inside a FreeSpec test,
     * if you for example have many tests that take rather long, and you wonder
     * which one is currently running.
     */
    trait RichFreeSpec extends FreeSpec {
    
      private var _currentTestName: Option[String] = None
      def currentTestName = _currentTestName getOrDie "DwE90RXP2"
    
      protected override def runTest(testName: String, args: org.scalatest.Args) {
        _currentTestName = Some(testName)
        super.runTest(testName, args)
      }
    }
    

提交回复
热议问题