14

I want to write functional test for my controller in PlayFramework. To do that I want to mock implementation of some classes.

I found nice example of how to do that using spec2 here: http://www.innovaedge.com/2015/07/01/how-to-use-mocks-in-injected-objects-with-guiceplayscala/

But I'm using scala test with OneAppPerSuite trait that uses FakeApplication. Here are documentation: https://www.playframework.com/documentation/2.4.x/ScalaFunctionalTestingWithScalaTest

Problem is that i cannot found a way to intercept into GuiceApplicationBuilder and override some bindings with mock implementation.

Here are FakeApplication implementation from play.api.test:

case class FakeApplication(
  override val path: java.io.File = new java.io.File("."),
  override val classloader: ClassLoader = classOf[FakeApplication].getClassLoader,
  additionalPlugins: Seq[String] = Nil,
  withoutPlugins: Seq[String] = Nil,
  additionalConfiguration: Map[String, _ <: Any] = Map.empty,
  withGlobal: Option[play.api.GlobalSettings] = None,
  withRoutes: PartialFunction[(String, String), Handler] = PartialFunction.empty) extends Application {

private val app: Application = new GuiceApplicationBuilder()
  .in(Environment(path, classloader, Mode.Test))
  .global(withGlobal.orNull)
  .configure(additionalConfiguration)
  .bindings(
    bind[FakePluginsConfig] to FakePluginsConfig(additionalPlugins, withoutPlugins),
    bind[FakeRouterConfig] to FakeRouterConfig(withRoutes))
  .overrides(
    bind[Plugins].toProvider[FakePluginsProvider],
    bind[Router].toProvider[FakeRouterProvider])
  .build

So there is no way for me to intercept into GuiceApplicationBuilder and override bindings.

I'm new to playframework so sorry if question looks a bit silly. Thanks!

Zygimantas Gatelis
  • 1,923
  • 2
  • 18
  • 27

2 Answers2

0

Take a look at GuiceOneAppPerTest. Here is an example (Play 2.8, scala 2.13):

abstract class MyBaseSpec extends PlaySpec with GuiceOneAppPerTest with Results with Matchers with MockFactory {

  def overrideModules: Seq[GuiceableModule] = Nil

  override def newAppForTest(testData: TestData): Application = {
    GuiceApplicationBuilder()
      .overrides(bind[ControllerComponents].toInstance(Helpers.stubControllerComponents()))
      .overrides(overrideModules: _*)
      .build()
  }
}
class OrderServiceSpec extends MyBaseSpec {
  val ordersService: OrdersService = mock[OrdersService]
  val usersService: UsersService = mock[UsersService]

  override def overrideModules = Seq(
    bind[OrdersService].toInstance(ordersService),
    bind[UsersService].toInstance(usersService),
  )

  // tests
  
}
Oleksandr Lykhonosov
  • 1,138
  • 12
  • 25
-1

You are probably using an older version of ScalaTestPlus, which didn't support overriding FakeApplication with Application. In Play docs(Play 2.4) the library version is "1.4.0-M3" but it should be "1.4.0".

insan-e
  • 3,883
  • 3
  • 18
  • 43