How to Test a Play Application that extends a custom trait

99封情书 提交于 2019-12-25 04:11:25

问题


I'm having trouble writing tests for a mixin to my Play application that runs in it's own thread separate from play. I've tried over-writing WithApplication.provideApplication method with no luck. I get an inheriting conflicting methods error. (one from the real app "MyRunnableSystemWrapper", one from my mocked fake mixin called "MyMockedSystemWrapper").

execute(system) runs my system that is tested elsewhere and has sideaffects (connects to networked services, thus failing this test when such things are not available. Good news is I have a mocked service of my system wrapper that uses a system which does NOT have side affects and DB/Network calls are mocked out. However I do not know how to give THIS MOCKED version of my app to "WithApplication" test.

Reduced Code for clarity:

class Application extends Controller with MyRunnableSystemWrapper {

  val pool: ExecutorService = Executors.newFixedThreadPool(1)
  val system = new MyRunnableSystem() //system is abstract in MRSW ^^^ above
  pool.execute(system)

  def index = Action {
    OK("HI")
  }
}

My Test:

class MyAppTest(implicit ee: ExecutionEnv) extends Specification  {

  abstract class WithMyMockApp extends WithApplication {
    def provideApplication = new controllers.Application with MyMockedSystemWrapper // This imports MyRunnableSystemWrapper 

  }

  "Sending a GET request" should {
    "Respond with OK" in new WithMyMockApp {
      val response = route(app, FakeRequest(GET, "/")).get
      status(response) mustEqual OK
    }
  }
}

If I'm not running my Runnable in the correct place and should be calling it somewhere else to make this testing easier, let me know!


回答1:


You could inject your system wrapper instead of extending it

trait SystemWrapper {
    def execute(system: RunnableSystem)
}

class MyRunnableSystemWrapper extends SystemWrapper {...}
class MyMockedSystemWrapper extends SystemWrapper {...}

class Application @Inject() (systemWrapper SystemWrapper) extends Controller {

Then you need to tell Guice which implementation of SystemWrapper you want for runtime and which one for test. One way of doing this is by using different Guice modules for runtime/test which you set in your .conf files.



来源:https://stackoverflow.com/questions/40924057/how-to-test-a-play-application-that-extends-a-custom-trait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!