在Play 2.6中对控制器进行单元测试 [英] Unit testing a controller in Play 2.6
问题描述
尝试在Scala的Play 2.6中测试控制器时,出现了空指针异常. 这是对OK响应的测试:
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.
日志输出为:
java.lang.NullPointerException was thrown.
java.lang.NullPointerException
at controllers.ApplicationController.home(ApplicationController.scala:29)
java.lang.NullPointerException was thrown.
java.lang.NullPointerException
at controllers.ApplicationController.home(ApplicationController.scala:29)
推荐答案
NPE是因为您正在使用mock[ControllerComponents]
.只需将其替换为stubControllerComponents()
,一切都会按预期进行.
NPE is because you are using mock[ControllerComponents]
. Just replace it with stubControllerComponents()
and things will work as expected.
当您调用未正确模拟的方法或访问字段时,在测试中会发生NPE.
NPE occurs in testing when you call methods or access fields which are not mocked properly.
我想你错过了读这篇文章. https://www.playframework.com/documentation/2.6.x/Highlights26# StubControllerComponents
I guess you missed reading this. https://www.playframework.com/documentation/2.6.x/Highlights26#StubControllerComponents
这篇关于在Play 2.6中对控制器进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!