Scala Play2 router/controller 在不访问数据库的情况下进行测试
Scala Play2 router/controller test without hitting database
我有一个通过路由器的简单控制器测试:
"returns all reservations" should {
running(FakeApplication()) {
val Some(result) = route(FakeRequest(GET, "/reservations?envId=560d89ec5393af5d00bcfdf1"))
mustBeValidResponse(result)
contentAsString(result) must contain("environmentId")
}
}
但是如您所见,它需要一个 ID 作为 URL 的一部分,这意味着我的测试依赖于数据库中的数据,这是不好的。我如何创建测试将 运行 反对的夹具或其他东西,以便测试 运行 不实际依赖数据库中的数据?
我假设访问数据库的代码不直接在控制器中,而是在注入控制器的另一个 class 中。您应该使用 Play 2.4 版中引入的模块系统。那么你需要的是用模拟替换访问数据库的真实实现。更多信息在这里:
https://www.playframework.com/documentation/2.4.x/ScalaTestingWithGuice#Overriding-bindings-in-a-functional-test
我有一个通过路由器的简单控制器测试:
"returns all reservations" should {
running(FakeApplication()) {
val Some(result) = route(FakeRequest(GET, "/reservations?envId=560d89ec5393af5d00bcfdf1"))
mustBeValidResponse(result)
contentAsString(result) must contain("environmentId")
}
}
但是如您所见,它需要一个 ID 作为 URL 的一部分,这意味着我的测试依赖于数据库中的数据,这是不好的。我如何创建测试将 运行 反对的夹具或其他东西,以便测试 运行 不实际依赖数据库中的数据?
我假设访问数据库的代码不直接在控制器中,而是在注入控制器的另一个 class 中。您应该使用 Play 2.4 版中引入的模块系统。那么你需要的是用模拟替换访问数据库的真实实现。更多信息在这里: https://www.playframework.com/documentation/2.4.x/ScalaTestingWithGuice#Overriding-bindings-in-a-functional-test