specs2 After method runs before the example

南笙酒味 提交于 2019-12-13 16:34:05

问题


I have the following test:

class Foo extends mutable.SpecificationWithJUnit {
sequential

"this example should run before the 'After' method" in new Context {
    bar must beSome
}

class Context extends mutable.BeforeAfter with mutable.Around {

  override def apply[T : AsResult](a: =>T): Result = {
  lazy val result = super[Around].apply(a)
  super[BeforeAfter].apply(result)
  }

  override def delayedInit(x: => Unit): Unit = around { try { before; x; Success() } finally { after }}

  @Resource var barReader : BarReader = _

  val bar = barReader.someBar

  override def before : Any = { //some stuff}

  def after: Any = {
    bar = None
  }

  override def around[T : AsResult](t: =>T) = {
     //spring context injection logic
     AsResult.effectively(t)
  }

  }
}
}

I expect this test to pass but in reality what happens is that because of the delayed init, the after runs before the example. If I change the Context to a trait I lose the delayed init functionality. Is this a bug or am I doing something wrong?

**Edited: This example will throw an NPE when the Context is a trait. What I expect to happen is that because of the delayed-init, the Context's constructor, which consequentially means the barReader.someBar will run only after the barReader has been injected.

Thanks Netta


回答1:


You should use a trait instead of a class for Context. If you use a class, delayedInit (hence after) will be triggered twice. Once for the body of the Context class and another time for the body of the anonymous class new Context. With a trait you don't get such a behavior:

class Foo extends mutable.SpecificationWithJUnit {
  sequential

  "this example should run before the 'After' method" in new Context {
    bar must beSome
  }

  trait Context extends mutable.After {
    var bar : Option[String] = Some("bar")

    def after: Any = bar = None
  }
}



回答2:


Simple answer, looks like this can't be done.



来源:https://stackoverflow.com/questions/21154941/specs2-after-method-runs-before-the-example

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