Scala 我们是否需要测试一个因异常而失败的公共方法的失败场景?
我有一个案例类Scala 我们是否需要测试一个因异常而失败的公共方法的失败场景?,scala,unit-testing,scalatest,scalamock,Scala,Unit Testing,Scalatest,Scalamock,我有一个案例类Employee 定义为案例类员工(……字段……) 我有办法说 def getEmployees(organization: String): Future[Seq[Employee]] = { val result = employeeClient.getAllEmployees(organization) // some logic on this list of Employees received from the client and manipul
Employee
定义为案例类员工(……字段……)
我有办法说
def getEmployees(organization: String): Future[Seq[Employee]] = {
val result = employeeClient.getAllEmployees(organization)
// some logic on this list of Employees received from the
client and manipulate it to get finalListOfEmployees and return it
to caller of `getEmployees`//
finalListOfEmployees
//end //
}
现在我使用scala mock测试getEmployees
。我没有处理来自getEmployees
的异常,也没有从中恢复。这意味着出现在客户机方法的getAllEmployees
处的异常将返回到getEmployees
的调用方
现在的问题是我们需要测试这方面吗
我的意思是,下面的测试是否增加了价值
"Fail with future" in { (mockEmployeeClient.getAllEmployees_).expects("SomeOrganization").returning(Future.failed(new Exception("failed"))
getEmployees("SomeOrganization).failed.futureValue.getMessage shouldBe "failed"
}
首先,如果您使用scala是因为您想使用函数式编程,那么最好以更实用的方式处理错误案例,例如使用Try monad包装对getAllEmployees的调用。
除此之外,测试必须覆盖应用程序的所有可能场景,以确保您的程序在这种情况下正常运行。因此,如果这个异常可能发生,也应该对它进行测试,测试方式与任何其他输出相同我认为我们应该测试它,因为这里的语义似乎是getEmployees
的调用方,期望失败由失败的未来
表示。现在考虑一下,如果有人会重构代码> GETSuffs会发生什么,这样就可以通过返回空列表<代码>将来(NIL)< /C>而不是像SO 来恢复<代码>
def getEmployees(organization: String): Future[Seq[Employee]] = {
val result = employeeClient.getAllEmployees(organization)
result.recover { case e => List.empty[Employee] }
...
}
一切都会像以前一样编译得很好,但突然之间语义就大不相同了。单元测试可以捕捉语义上的这种变化,并提示我们适当地删除重构或更新getEmployees
的调用方。我从来都不喜欢mock,因为这里没有测试任何东西。测试越多,覆盖的案例越多,应用程序就越好。