ChazMcDingle
ChazMcDingle

Reputation: 675

Unit testing a controller in Play 2.6

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)

Upvotes: 4

Views: 3676

Answers (2)

saheb
saheb

Reputation: 599

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

Upvotes: 8

NateH06
NateH06

Reputation: 3574

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.

Upvotes: 0

Related Questions