roundcrisis
roundcrisis

Reputation: 17805

ScalaTest test name without fixture?

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

Upvotes: 4

Views: 965

Answers (3)

Boris Azanov
Boris Azanov

Reputation: 4491

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.

Upvotes: 1

Alexey Romanov
Alexey Romanov

Reputation: 170775

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())

Upvotes: 4

roundcrisis
roundcrisis

Reputation: 17805

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

Upvotes: 0

Related Questions