jack miao
jack miao

Reputation: 1498

How to inject Configuration instance to scalatest?

I want to inject Configuration instance in one of my testing classes, I extend my test class with ConfiguredApp and injected the Configuration, it looks like this:

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

Exception encountered when invoking run on a nested suite - ConfiguredApp needs an Application value associated with key "org.scalatestplus.play.app" in the config map. Did you forget to annotate a nested suite with @DoNotDiscover? java.lang.IllegalArgumentException: ConfiguredApp needs an Application value associated with key "org.scalatestplus.play.app" in the config map. Did you forget to annotate a nested suite with @DoNotDiscover?

someone have an idea why is that...?

thanks!333333

Upvotes: 2

Views: 2352

Answers (2)

Bunyod
Bunyod

Reputation: 1371

My answer is not answer to current question, but I want give some advice. If you want to write unit tests for controllers or some service, I would suggest to use a PlaySpec. In order to inject custom configuration for testing environment:

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

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

}

Upvotes: 2

pme
pme

Reputation: 14803

It seems that you tried to run this test alone. But with a ConfiguredAppyou must run this test with a Suite, like

class AcceptanceSpecSuite extends PlaySpec with GuiceOneAppPerSuite {

  override def nestedSuites = Vector(new MyApiServiceSpec)
}

The injection looks ok.

Upvotes: 0

Related Questions