2

我正在寻找一种将依赖项注入测试(在 /tests/models/ 中)的方法,如下所示:

class FolderSpec(implicit inj: Injector) extends Specification with Injectable{

  val folderDAO = inject [FolderDAO]

  val user = User(Option(1), LoginInfo("key", "value"), None, None)

  "Folder model" should {

    "be addable to the database" in new WithFakeApplication {
      folderDAO.createRootForUser(user)
      val rootFolder = folderDAO.findUserFolderTree(user)
      rootFolder must beSome[Folder].await
    }

  }
}

在哪里

abstract class WithFakeApplication extends WithApplication(FakeApplication(additionalConfiguration = inMemoryDatabase()))

/app/modules/WebModule:

class WebModule extends Module{
  bind[FolderDAO] to new FolderDAO
}

/应用程序/全球:

object Global extends GlobalSettings with ScaldiSupport with SecuredSettings with Logger {
  def applicationModule = new WebModule :: new ControllerInjector
}

但是在编译时我有以下堆栈跟踪:

[error] Could not create an instance of models.FolderSpec
[error]   caused by java.lang.Exception: Could not instantiate class models.FolderSpec: argument type mismatch
[error]   org.specs2.reflect.Classes$class.tryToCreateObjectEither(Classes.scala:93)
[error]   org.specs2.reflect.Classes$.tryToCreateObjectEither(Classes.scala:207)
[error]   org.specs2.specification.SpecificationStructure$$anonfun$createSpecificationEither$2.apply(BaseSpecification.scala:119)
[error]   org.specs2.specification.SpecificationStructure$$anonfun$createSpecificationEither$2.apply(BaseSpecification.scala:119)
[error]   scala.Option.getOrElse(Option.scala:120)

可悲的是,我在 Scaldi 文档中没有找到任何关于此事的信息。

有没有办法在测试中注入东西?

4

1 回答 1

1

Scaldi 不提供与任何测试框架的集成,但实际上您通常不需要它。在这种情况下,您可以做的是创建一个Module包含模拟和存根(如内存数据库)的测试,然后只GlobalFakeApplication. 这是一个如何做到这一点的例子:

"render the index page" in {
  class TestModule extends Module {
    bind [MessageService] to new MessageService {
      def getGreetMessage(name: String) = "Test Message"
    }
  }

  object TestGlobal extends GlobalSettings with ScaldiSupport {

    // test module will override `MessageService`
    def applicationModule = new TestModule :: new WebModule :: new UserModule
  }

  running(FakeApplication(withGlobal = Some(TestGlobal))) {
    val home = route(FakeRequest(GET, "/")).get

    status(home) must equalTo(OK)
    contentType(home) must beSome.which(_ == "text/html")

    println(contentAsString(home))

    contentAsString(home) must contain ("Test Message")
  }
}

您可以在scaldi-play-example 应用程序中找到此代码。

于 2014-10-21T19:14:21.970 回答