如何将配置实例注入到scalatest?

时间:2016-10-06 00:55:11

标签: scala playframework playframework-2.0 guice scalatest

我想在我的一个测试类中注入Configuration实例,我使用ConfiguredApp扩展我的测试类并注入Configuration,它看起来像这样:

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

在嵌套套件上调用run时遇到异常 -   ConfiguredApp需要与key关联的Application值   " org.scalatestplus.play.app"在配置图中。你忘记了吗?   使用@DoNotDiscover注释嵌套套件?   java.lang.IllegalArgumentException:ConfiguredApp需要一个Application   与键相关联的值" org.scalatestplus.play.app"在配置中   地图。您是否忘记使用@DoNotDiscover注释嵌套套件?

有人知道为什么会这样......?

谢谢!333333

2 个答案:

答案 0 :(得分:1)

我的回答不是当前问题的答案,但我想提出一些建议。如果你想为控制器或某些服务编写单元测试,我建议使用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
        }
    }

}

答案 1 :(得分:0)

您似乎试图单独运行此测试。但是使用ConfiguredApp,您必须使用套件运行此测试,例如

class AcceptanceSpecSuite extends PlaySpec with GuiceOneAppPerSuite {

  override def nestedSuites = Vector(new MyApiServiceSpec)
}

注射看起来不错。