How stub and mock object generation works
series/7.xScalamock uses compile-time generation to create stubs and mocks. For any provided trait or class definition, Scalamock generates an implementation that stores state internally. This state is updated whenever an expectation is set or a method is invoked.
There are two primary internal approaches depending on the API used:
- New Stubs: Uses a
StubbedMethod[Args, Result]for each method. If a method has multiple arguments, they are internally handled as a tuple. To simplify generation, these are stored asStubbedMethod[Any, Any]and cast to the correct type at runtime. - Classic API: Uses specific function types based on the exact number of arguments (e.g.,
MockFunction1,MockFunction2, up toMockFunction22). This allows the public API to provide type-safe argument matching (e.g.,expects(*, *)).
trait Foo:
def oneArg(x: Int): Int
def twoArgs(x: Int, y: String): String
def curried(x: Int)(y: String): Int
val foo = stub[Foo]