ScalaMock: how to taunt / stifle a method to return different values ​​per call?

Using ScalaMock, I want the mock / stub class method to return a different value for each call (call order).

I can achieve this with mockand expects, but it will make me test these challenges.

Can I do this with help stub?

Also, how can I say something like "first return X and then always return Y" (both with mockand stub)?

+4
source share
2 answers

Yes, it can be done, although the syntax is a bit unintuitive:

    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 fine that we don't call it a fourth time - calls are not verified.

.noMoreThanOnce(), .once(), . .noMoreThanTwice(), , .noMoreThanNTimes() .


" X, Y" mocks stubs:

    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")
+4

, , - onCall - . , anyNumberOfTimes repreted(...).

import org.scalamock.scalatest.MockFactory

trait Foo {
  def getSomeValue(param1: Any, param2: Any): String
}

class Test extends MockFactory {
  val fooMock = stub[Foo]

  val it = Iterator.single("X") ++ Iterator.continually("Y")

  (fooMock.getSomeValue _)
    .expects(*, *)
    .onCall((p1, p2) => it.next())
    .anyNumberOfTimes
}

fooMock.someValue(...) X Y.

+2

Source: https://habr.com/ru/post/1619077/


All Articles