【问题标题】:How to access test/example/fragment name in Specs2 before and after methods?如何在方法之前和之后访问 Specs2 中的测试/示例/片段名称?
【发布时间】:2014-02-18 23:39:09
【问题描述】:

我想做这样的事情:

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

【问题讨论】:

    标签: scala specs2


    【解决方案1】:

    这可能会起作用:

    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,我认为你无法在 before 和 after 方法中获得太多上下文。

    【讨论】:

    • 由于为每个示例制作了规范的副本,因此这不起作用。 OTOH,您的回答有帮助,因为它为我提供了有关 specs2 如何工作的更多背景信息。我可以在 beforeSpec 和 afterSpec 中创建和销毁目录。
    【解决方案2】:

    您可以使用 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 开头的包中直接创建你的工厂来解决这个限制,使用较新的 specs2 版本) .

    【讨论】:

      【解决方案3】:

      有点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()
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-25
        • 2020-11-17
        • 2013-09-08
        • 1970-01-01
        • 2020-01-20
        相关资源
        最近更新 更多