dimanche 1 décembre 2019

Testing Play controller with query parameter

given a simple Play controller that handles a query parameter, i.e.

class MyController @Inject()(val controllerComponents: ControllerComponents) extends BaseController {
  def foo(name: Option[String]) = { ... } 
}

how should I test that foo works properly and gets the correct query parameter, using ScalaTest, and without instantiating a FakeApplication ?

The closest I've come with, is the following:

class MyControllerSpec extends FlatSpec with StubControllerComponentsFactory with Results with Matchers {
  private val controller = new MyController(stubControllerComponents())

  it should "read `name` query parameter" in {
    val result = controller.foo().apply(FakeRequest("GET", "/?name=test"))
    contentAsString(result) shouldBe ...
  }
}

but, as you know, this won't work: FakeRequest content will get ignored, and I must explicitly call the controller as controller.foo(Some("test")).apply(...) which doesn't look good, nor logical.

I have a feeling that, since it's done at routing level, I will have to use a FakeApplication... but maybe I'm wrong, and somebody knows a way to achieve what I'm looking for.

Thanks!

Aucun commentaire:

Enregistrer un commentaire