【问题标题】:How to test an injected class through Spec2?如何通过 Spec2 测试注入的类?
【发布时间】:2016-12-09 13:08:18
【问题描述】:

我正在尝试测试一个类

@Singleton
class Foo @Inject()(bar: Bar)(implicit ec: ExecutionContext) {
  def doSomething = bar.doSomethingInBar
}

class Bar {
  def doSomethingInBar = true
}

通过下面提到的Specification

class FooTest @Inject()(foo: Foo) extends Specification {
  "foo" should {
    "bar" in {
      foo.doSomething mustEqual (true)
    }
  }
}

现在当我运行它时,我得到以下错误

Can't find a constructor for class Foo

我关注了the solution mentioned here

并定义了Injector

object Inject {
  lazy val injector = Guice.createInjector()

  def apply[T <: AnyRef](implicit m: ClassTag[T]): T =
    injector.getInstance(m.runtimeClass).asInstanceOf[T]
}

和我的规范类中的lazy val foo: Foo = Inject[Foo]。它解决了我的构造函数初始化问题,但我现在收到此错误。

[error]   ! check the calculate assets function
[error]    Guice configuration errors:
[error]    
[error]    1) No implementation for scala.concurrent.ExecutionContext was bound.
[error]      while locating scala.concurrent.ExecutionContext

【问题讨论】:

    标签: scala spec2


    【解决方案1】:

    您需要提供隐式ExecutionEnv 才能使代码正常工作

    @RunWith(classOf[JUnitRunner])
    class FooTest(implicit ee: ExecutionEnv)  extends Specification {
      "foo" should {
        "bar" in {
          foo.doSomething mustEqual (true)
        }
      }
    }
    

    现在在你的代码中的某个地方,你需要初始化 foo 构造,你可以将它传递给构造函数——这就是依赖注入的关键。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 1970-01-01
      • 1970-01-01
      • 2012-12-23
      相关资源
      最近更新 更多