如何通过 Spec2 测试注入的 class?

How to test an injected class through Spec2?

我正在尝试测试 class

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

class Bar {
  def doSomethingInBar = true
}

通过下面提到的 Specification class

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

现在,当我 运行 出现以下错误时

Can't find a constructor for class Foo

我关注了

并定义了一个Injector

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

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

和我的规范 class 中的 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

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

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

现在在您的代码中的某处,您需要初始化 foo 构造,您可以通过构造函数传递它 - 这就是依赖注入的意义所在。