首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >单元测试某些任务是在过程中完成的。

单元测试某些任务是在过程中完成的。
EN

Software Engineering用户
提问于 2017-12-22 14:08:28
回答 1查看 174关注 0票数 0

我有一些Scala代码,我希望使用ScalaMock进行单元测试:

代码语言:javascript
复制
class CancellationManagerSpec extends FlatSpec with MockFactory {

  "Cancelling a shipment" should "check shipment is not already shipped" in {

    val manager = mock[CancellationsManager]
    (manager.checkStatus _).expects(*, *).returning(true).once()

    val request = CancellationRequestedEvent("shipmentNumber")
    manager.processCancellation(request)
  }
}

测试失败:

代码语言:javascript
复制
[info] - should complete a series of tasks in happy case *** FAILED ***
[info]   Unexpected call: <mock-6> CancellationsManager.processCancellation(CancellationRequestedEvent(shipmentNumber))
[info]   
[info]   Expected:
[info]   inAnyOrder {
[info]     <mock-6> CancellationsManager.checkStatus(*, *) once (never called - UNSATISFIED)
[info]   }
[info]   
[info]   Actual:
[info]     <mock-6> CancellationsManager.processCancellation(CancellationRequestedEvent(shipmentNumber)) (Option.scala:121)

我想测试,当我处理取消时,某些任务已经完成。更广泛地说,有这样的逻辑我想要测试:

代码语言:javascript
复制
class SalesOrderShippedProcess {
  def execute(salesOrder: SalesOrder): Unit = {
    if (doTask1() && doTask2()) {
      doTask3()
      doTask4()
      doTask5()
    }
  }

  def doTask1(): Boolean = ???
  def doTask2(): Boolean = ???
  def doTask3(): Boolean = ???
  def doTask4(): Boolean = ???
  def doTask5(): Boolean = ???
}

对于某些进程,我想要检查任务3、4和5只在任务1和2成功时才能完成,即使任务3失败,任务4和5也应该执行。

最好的测试方法是什么?因为我直接调用模拟对象的方法,所以失败了吗?我是否需要将所有的任务方法移到它自己的类中,然后模拟它,这对我来说有点奇怪,只是为了能够为它编写一个测试?

EN

回答 1

Software Engineering用户

发布于 2017-12-22 14:44:02

是的,您这样做是错误的-您应该在实际对象上调用一个方法(在您的例子中是CancellationsManager ),而不是在模拟上。所以你的测试看起来有点像:

代码语言:javascript
复制
it should "check the status when an order is cancelled" in {
  val manager = new CancellationManager();
  val request = new CancellationRequestedEvent("shipmentId");

  manager.processCancellation(request);

  (manager.checkStatus _).expects(*, *).returning(true).once()
}

模拟的存在是为了替换被测试对象的依赖关系,而不是对象本身--例如,如果您的CancellationManager依赖于一个ShipmentFinder,您将模拟出ShipmentFinder,以便您只测试CancellationManager代码,而不是它的所有依赖项。

票数 1
EN
页面原文内容由Software Engineering提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://softwareengineering.stackexchange.com/questions/362859

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档