2014-10-20 89 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