3

我想做类似的事情:

class MySpec extends Specification with BeforeAfterExample {
  var testName
  var clientDir

  def before {
    testName = fragmentName.replaceAll(" ", "-")
    clientDir = new File(workspaceRoot, testName)
    clientDir.mkdirs()
  }

  def after {
    FileUtils.deleteDirectory(clientDir)
  }
}
4

3 回答 3

0

您可以使用 specs2 做您想做的事ExampleFactory

import org.specs2._
import specification._

class TestSpec extends Specification { def is =
  "test" ! {
    ok
  }
  case class BeforeAfterExample(e: Example) extends BeforeAfter {
    def before = println("before "+e.desc)
    def after  = println("after "+e.desc)
  }
  override def exampleFactory = new ExampleFactory {
    def newExample(e: Example) = {
      val context = BeforeAfterExample(e)
      e.copy(body = () => context(e.body()))
    }
  }
}

API 的这一部分最近才开放,因此目前仅在 1.15-SNAPSHOT 中可用(您可以通过直接在以org.specs2.

于 2013-04-20T00:49:16.200 回答
0

有点hacky,但这对我有用:

/**
 * Returns the name of the currently executing example
 */
def getCurrentExampleName(spec: Specification): String = {

  val stack = new Exception().getStackTrace
  val specLinesUpStack = for (
    line <- stack
      if line.getClassName.startsWith(spec.getClass.getName))
        yield line.getLineNumber

  spec.is.examples
    .find(e => specLinesUpStack.contains(e.location.lineNumber))
    .get
    .desc.toString()
}
于 2014-02-18T15:39:09.187 回答
0

这可能会起作用:

class MySpec extends Specification with BeforeAfterExample {
  var currentExample = 0
  var testName = ""
  var clientDir:File = null

  def before {
    testName = is.examples(currentExample).desc.toString.replaceAll(" ", "-")
    clientDir = new File(workspaceRoot, testName)
    clientDir.mkdirs()
  }

  def after {
    FileUtils.deleteDirectory(clientDir)
    currentExample += 1    
  }
}

我不认为你可以在之前和之后的方法中获得很多上下文而不做一些像这样的hacky。

于 2013-04-18T15:57:03.687 回答