使用ScalaMock,我想模拟/存根一个类方法,因此它将为每次调用返回一个不同的值(调用顺序很重要).
我可以用mock
和实现这一点expects
,但这将迫使我验证这些调用.
我可以这样做stub
吗?
另外,我怎么能说"第一次返回X,然后总是返回Y"(两者都带有mock
和stub
)?
是的,这可以做到,虽然语法有点不直观:
trait Foo { def getInt: Int } val fooStub = stub[Foo] (fooStub.getInt _).when().returns(1).noMoreThanOnce() (fooStub.getInt _).when().returns(2).noMoreThanOnce() (fooStub.getInt _).when().returns(3) (fooStub.getInt _).when().returns(4) assert(fooStub.getInt == 1) assert(fooStub.getInt == 2) assert(fooStub.getInt == 3) // Note that it's fine that we don't call it a fourth time - calls are not verified.
使用.noMoreThanOnce()而不是.once()很重要,否则会导致调用被验证.还有一个.noMoreThanTwice()方法,但我认为没有.noMoreThanNTimes()或任何等价物.
这里是如何做"第一次返回X,然后总是返回Y"的模拟和存根:
trait Bar { def getString: String } val barMock = mock[Bar] (barMock.getString _).expects().returning("X") (barMock.getString _).expects().returning("Y").anyNumberOfTimes() assert(barMock.getString == "X") assert(barMock.getString == "Y") assert(barMock.getString == "Y") val barStub = stub[Bar] (barStub.getString _).when().returns("x").noMoreThanOnce() (barStub.getString _).when().returns("y") assert(barStub.getString == "x") assert(barStub.getString == "y") assert(barStub.getString == "y")