首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过Spec2测试注入类?

如何通过Spec2测试注入类?
EN

Stack Overflow用户
提问于 2016-12-09 13:08:18
回答 1查看 160关注 0票数 0

我正试着测试一堂课

代码语言:javascript
复制
@Singleton
class Foo @Inject()(bar: Bar)(implicit ec: ExecutionContext) {
  def doSomething = bar.doSomethingInBar
}

class Bar {
  def doSomethingInBar = true
}

通过下面提到的Specification

代码语言:javascript
复制
class FooTest @Inject()(foo: Foo) extends Specification {
  "foo" should {
    "bar" in {
      foo.doSomething mustEqual (true)
    }
  }
}

现在,当我运行这个程序时,我会得到以下错误

代码语言:javascript
复制
Can't find a constructor for class Foo

我跟着the solution mentioned here

并定义了一个Injector

代码语言:javascript
复制
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]在我的规范类中。它解决了我的构造函数初始化问题,但我现在得到了这个错误。

代码语言:javascript
复制
[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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-14 05:27:41

您需要提供一个隐式ExecutionEnv来使代码工作。

代码语言:javascript
复制
@RunWith(classOf[JUnitRunner])
class FooTest(implicit ee: ExecutionEnv)  extends Specification {
  "foo" should {
    "bar" in {
      foo.doSomething mustEqual (true)
    }
  }
}

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41061241

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档