Unit testing a controller in Play 2.6

我的梦境 提交于 2019-12-23 12:34:42

问题


I'm getting a null pointer exception when trying to test a controller in Play 2.6 in Scala. This is a test for an OK response:

class ApplicationControllerSpec extends PlaySpec
with MockitoSugar with ScalaFutures {

  val mockOrchestrator = mock[ApplicationOrchestrator]
  val mockCC = mock[ControllerComponents]
  val controller = new ApplicationController(mockOrchestrator, mockCC)
  val method = controller.home()(FakeRequest())

  assert(status(method) == 200)
}

This is the Controller I'm testing:

class ApplicationController @Inject()
(orchestrator: ApplicationOrchestrator, cc: ControllerComponents)
extends AbstractController(cc) with I18nSupport {

    def home(): Action[AnyContent] = Action {
      implicit request: RequestHeader => //line 29
        Ok(views.html.home())
    }
}

The error looks like it is associated with the implicit request but I cannot find a solution.

The log output is:

java.lang.NullPointerException was thrown. java.lang.NullPointerException at controllers.ApplicationController.home(ApplicationController.scala:29)


回答1:


NPE is because you are using mock[ControllerComponents]. Just replace it with stubControllerComponents() and things will work as expected.

NPE occurs in testing when you call methods or access fields which are not mocked properly.

I guess you missed reading this. https://www.playframework.com/documentation/2.6.x/Highlights26#StubControllerComponents




回答2:


The method expects a request to be fed into it, and you haven't fed it a valid request. It looks like you need to feed some parameters into the FakeRequest.

If in your routes.conf file you have that controller's method wired as:

GET /home controllers.ApplicationController.home

Then in your unit test this line:

val method = controller.home()(FakeRequest())

should really be:

val method = controller.home().apply(FakeRequest(GET, "/home"))

and you should now be able to run your test as expected.



来源:https://stackoverflow.com/questions/44972670/unit-testing-a-controller-in-play-2-6

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