我有一些Scala代码,我希望使用ScalaMock进行单元测试:
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)
}
}测试失败:
[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)我想测试,当我处理取消时,某些任务已经完成。更广泛地说,有这样的逻辑我想要测试:
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也应该执行。
最好的测试方法是什么?因为我直接调用模拟对象的方法,所以失败了吗?我是否需要将所有的任务方法移到它自己的类中,然后模拟它,这对我来说有点奇怪,只是为了能够为它编写一个测试?
发布于 2017-12-22 14:44:02
是的,您这样做是错误的-您应该在实际对象上调用一个方法(在您的例子中是CancellationsManager ),而不是在模拟上。所以你的测试看起来有点像:
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代码,而不是它的所有依赖项。
https://softwareengineering.stackexchange.com/questions/362859
复制相似问题