2016-10-06 102 views
1

我想在我的測試類之一注入Configuration實例,我向我的ConfiguredApp測試類和注入配置,它看起來像這樣:如何將配置實例注入scalatest?

@DoNotDiscover() 
class MyApiServiceSpec extends FreeSpec with ScalaFutures with ConfiguredApp { 

    implicit val formats = DefaultFormats 

    implicit val exec = global 

    lazy val configuration = app.injector.instanceOf[Configuration] 

    "Global test" - { 

    "testcase 1" in { 

     Server.withRouter() { 
     case GET(p"/get/data") => Action { request => 
      Results.Ok() 
     } 
     } { implicit port => 
     WsTestClient.withClient { implicit client => 
      val service = new MyApiService { 
      override def config: Configuration = configuration 
      override val ws: WSClient = client 
      } 


      whenReady(service.getData()) { res => 
//i will test stuff here 
      } 
     } 
     } 
    } 
    } 
} 

(MyApiService is a trait) 

異常在嵌套套件調用運行時遇到 - ConfiguredApp需要與配置圖中的密鑰 「org.scalatestplus.play.app」關聯的應用程序值。你忘了 用@DoNotDiscover註釋一個嵌套套件嗎? java.lang.IllegalArgumentException:ConfiguredApp需要在配置 映射中與關鍵字「org.scalatestplus.play.app」關聯的應用程序 值。你忘了用@DoNotDiscover註釋一個嵌套套件嗎?

有人有一個想法,爲什麼是...?

感謝!333333

+0

可疑類似:https://stackoverflow.com/questions/39878662/fail-to-inject-configuration-to-scalatest-play-2-5 – rethab

回答

0

我的答案是不回答當前問題,但我想給一些建議。如果你想爲控制器或某種服務編寫單元測試,我會建議使用PlaySpec。爲了給測試環境注入自定義配置:

class TdiFnolControllerSpec extends PlaySpec with OneAppPerSuite { 

    val myConfigFile = new File("app/test/conf/application_test.conf") 
    val parsedConfig = ConfigFactory.parseFile(myConfigFile) 
    val configuration = ConfigFactory.load(parsedConfig) 

    implicit override lazy val app: Application = new GuiceApplicationBuilder() 
    .overrides(bind[Configuration].toInstance(Configuration(configuration))) 
    .build() 

    "YourControlelr #index" should { 
     "should be open" in { 
      val result = route(app, FakeRequest(GET, controllers.routes.YourController.index().url)).get 
      status(result) mustBe OK 
     } 
    } 

} 
0

看來你試圖單獨運行這個測試。但是隨着ConfiguredApp你必須用套件運行這個測試,比如

class AcceptanceSpecSuite extends PlaySpec with GuiceOneAppPerSuite { 

    override def nestedSuites = Vector(new MyApiServiceSpec) 
} 

注射看起來確定。