2016-10-06 51 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) 
} 

注射看起来确定。