关于scala:如何通过Spec2测试注入的类?

How to test an injected class through Spec2?

我正在尝试测试课程

1
2
3
4
5
6
7
8
@Singleton
class Foo @Inject()(bar: Bar)(implicit ec: ExecutionContext) {
  def doSomething = bar.doSomethingInBar
}

class Bar {
  def doSomethingInBar = true
}

通过下面提到的Specification

1
2
3
4
5
6
7
class FooTest @Inject()(foo: Foo) extends Specification {
 "foo" should {
   "bar" in {
      foo.doSomething mustEqual (true)
    }
  }
}

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

1
Can't find a constructor for class Foo

我遵循了此处提到的解决方案

并定义一个Injector

1
2
3
4
5
6
object Inject {
  lazy val injector = Guice.createInjector()

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

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

1
2
3
4
5
[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来使代码正常工作

1
2
3
4
5
6
7
8
@RunWith(classOf[JUnitRunner])
class FooTest(implicit ee: ExecutionEnv)  extends Specification {
 "foo" should {
   "bar" in {
      foo.doSomething mustEqual (true)
    }
  }
}

现在在代码中的某处,您需要初始化foo构造,然后可以将其传递给构造函数-这就是进行依赖注入的要点。