2014-10-20 51 views
1

我正在寻找一种方式来注入的依赖到测试(在/测试/模型/),看起来像以下:注入依赖于测试中播放框架,scaldi

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())) 

/应用程序/模块/ 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文档中的任何事情。

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

回答

1

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

"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 application此代码。

+0

这就是我在scaldi-play-example回购中看到的,但是我没有找到如何在测试类本身中明确注入东西。我在说我的例子中的这条线“val folderDAO = inject [FolderDAO]”。如何做呢? 您是否有任何计划在Play框架中进行测试集成? – Mironor 2014-10-22 05:05:35

+0

或者这可能是个坏主意,我不应该在测试类中进行明确的注射? – Mironor 2014-10-22 16:27:53

+0

@Mironor的确如此。当我考虑这个问题时,如果测试本身被注入,那么你需要某种全局测试模块,所有测试都是绑定的,或者至少应该有一些全局注入器可用于所有测试。这意味着您需要为其中的所有测试定义所有可能的模拟。在大多数情况下是不实际的。我建议保持测试模块的范围更小,就像我在例子中展示的那样 - 它为这个特定的测试用例定义了一个模块。但你也可以在整个测试课上做。 – tenshi 2014-10-22 18:37:53