0

我正在尝试测试一门课程

@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

我按照这里提到的解决方案

并定义了一个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
4

1 回答 1

0

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

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

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

于 2016-12-14T05:27:41.057 回答