Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 475
ChazMcDingle Avatar asked Jan 31 '23 01:01

ChazMcDingle


1 Answers

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

like image 135
saheb Avatar answered Feb 05 '23 18:02

saheb