【问题标题】:Do we need to test a failure scenario of a public method which fails with an Exception?我们是否需要测试因异常而失败的公共方法的失败场景?
【发布时间】:2019-11-18 14:58:15
【问题描述】:

我有一个案例类Employee 定义为case class Employee(.........fields.....) 我有一个方法说

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 或来自recovering 的异常。这意味着出现在客户端方法getAllEmployees 的异常将返回给getEmployees 的调用者。

现在的问题是我们需要测试这方面吗?

我的意思是下面的测试是否增加了任何价值??

"Fail with future" in {  (mockEmployeeClient.getAllEmployees_).expects("SomeOrganization").returning(Future.failed(new Exception("failed"))
          getEmployees("SomeOrganization).failed.futureValue.getMessage shouldBe "failed"
}

【问题讨论】:

  • 我从不喜欢模拟,因为你只是没有在这里测试任何东西。
  • 你做的测试越多,覆盖的案例越多,你的应用就越好。

标签: scala unit-testing scalatest scalamock


【解决方案1】:

我认为我们应该对其进行测试,因为这里的语义似乎是getEmployees 的调用者期望失败由失败的Future 表示。现在考虑如果有人重构 getEmployees 会发生什么情况

def getEmployees(organization: String): Future[Seq[Employee]] = {
 val result = employeeClient.getAllEmployees(organization)
 result.recover { case e => List.empty[Employee] }
 ...
}

一切都会像以前一样编译得很好,但突然间语义完全不同了。单元测试可以捕捉到这种语义变化,并提示我们适当地删除getEmployees 的重构或更新调用者。

【讨论】:

    【解决方案2】:

    首先,如果您因为想使用函数式编程而使用 scala,最好以更函数式的方式处理错误情况,例如使用 Try monad 包装对 getAllEmployees 的调用。 除此之外,测试必须涵盖应用程序的所有可能场景,以确保您的程序在这种情况下能够正常运行。因此,如果可能发生此异常,也应该对其进行测试,方法与任何其他输出相同

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 2014-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-27
      • 1970-01-01
      相关资源
      最近更新 更多