带有模拟对象的ScalaTest



我找到了一些简单的例子,但什么都不起作用。

一种型号:

class Product() {
var price: Int = 0
var stock: Int = 0
def addPrice(price: Int): Int = {
this.price = price
this.price
}
def addStock(qty: Int): Int = {
this.stock += qty
this.stock
}
}

和我的测试班

classProductSpec extends AnyFlatSpec with MockFactory with OneInstancePerTest {
val m = mock[Product]
// suites (test examples)
inAnyOrder {
(m.addPrice _).expects(40).returns(40).once
inSequence {
(m.addStock _).expects(20).returns(20).once
(m.addStock _).expects(10).returns(30).once
}
}
// tests
it should "set price" in {
assert(m.addPrice(40) == 40)
}
it should "add new qty. Step 1" in {
assert(m.addStock(20) == 20)
}
it should "add new qty. Step 2" in {
assert(m.addStock(10) == 30)
}
}

每次,错误都是:

Expected:
inAnyOrder {
inAnyOrder {
<mock-1> Product.addPrice(40) once (never called - UNSATISFIED)
...
}
}

如果我只运行一个套件和一个断言,它就可以工作:

(m.addPrice _).expects(40).returns(40).once
// tests
it should "set price" in {
assert(m.addPrice(40) == 40)
}

让我们解释一下上面的代码。inAnyOrder部分为所有测试定义断言。这意味着,在套件中的每个测试中,您都应该调用一次:

  1. m.addPrice(40)
  2. m.addStock(20)
  3. m.addStock(10)

而2必须在3之前。因此,由于缺少2个调用,每个测试都会失败。例如,测试:

it should "add new qty. Step 1" in {
assert(m.addStock(20) == 20)
}

失败,并显示消息:

Expected:
inAnyOrder {
inAnyOrder {
<mock-1> Product.addPrice(40) once (never called - UNSATISFIED)
inSequence {
<mock-1> Product.addStock(20) once (called once)
<mock-1> Product.addStock(10) once (never called - UNSATISFIED)
}
}
}
Actual:
<mock-1> Product.addStock(20)
ScalaTestFailureLocation: ProductSpec at (ProductSpec.scala:20)
org.scalatest.exceptions.TestFailedException: Unsatisfied expectation:

因为1和3不满意。

如果你要尝试这样的测试:

it should "set price" in {
assert(m.addPrice(40) == 40)
assert(m.addStock(20) == 20)
assert(m.addStock(10) == 30)
}

它会过去的。请注意,如果您更改2&3,同样的测试将失败。

相关内容

  • 没有找到相关文章

最新更新