Skip to content

Instantly share code, notes, and snippets.

@ShaneDelmore
Created March 2, 2016 23:36
Show Gist options
  • Save ShaneDelmore/230c1705d3dbe2bd45e4 to your computer and use it in GitHub Desktop.
Save ShaneDelmore/230c1705d3dbe2bd45e4 to your computer and use it in GitHub Desktop.
Stateful mocking, useful for mocking database calls and other stateful things with ScalaMock
//Paste into a scala worksheet to run
import org.scalatest.FlatSpec
import org.scalatest.ShouldMatchers
import org.scalamock.scalatest.MockFactory
trait Foo {
def getFoo: Int
}
object Test extends FlatSpec with ShouldMatchers with MockFactory {
val fooMock = stub[Foo]
//Example of mock instead of stub commented out
// val fooMock = mock[Foo]
var counter = 0
def getNext = {
counter = counter + 1
counter - 1
}
(fooMock.getFoo _).when().onCall(_ => getNext)
// (fooMock.getFoo _).expects().anyNumberOfTimes().onCall(_ => getNext)
}
Test.fooMock.getFoo //0
Test.fooMock.getFoo //1
Test.fooMock.getFoo //2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment