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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With