Skip to content

Instantly share code, notes, and snippets.

@missingfaktor
Created June 25, 2015 11:17
Show Gist options
  • Select an option

  • Save missingfaktor/ee6ae1cb25312fe5a915 to your computer and use it in GitHub Desktop.

Select an option

Save missingfaktor/ee6ae1cb25312fe5a915 to your computer and use it in GitHub Desktop.
package nope.utils
trait Stub {
class StubbedNullaryMethod[R] {
@volatile
protected var _function: () => R = () => throw new RuntimeException("Unset.")
def setFunction(f: () => R) {
_function = f
}
def setValue(value: R) {
_function = () => value
}
def get: R = _function()
}
class PartialFunctionInterceptor[A, R] extends PartialFunction[A, R] {
@volatile
private var _value: PartialFunction[A, R] = PartialFunction.empty
@volatile
private var _invocations: Seq[A] = Vector.empty
def invocations = _invocations
def apply(arg: A): R = {
_invocations +:= arg
_value.apply(arg)
}
def addCases(newCases: PartialFunction[A, R]) {
_value = _value orElse newCases
}
override def isDefinedAt(arg: A): Boolean = _value.isDefinedAt(arg)
}
abstract class StubbedMethod[A, R] {
protected val underlyingImplementation = new PartialFunctionInterceptor[A, R]
def invocationCount(f: A => Boolean = Function.const(true)) = {
underlyingImplementation.invocations.count(f)
}
def setExpectations(pf: PartialFunction[A, R]) {
underlyingImplementation.addCases(pf)
}
}
final class StubbedMethod2[A1, A2, R] extends StubbedMethod[(A1, A2), R] {
def apply(arg1: A1, arg2: A2): R = {
underlyingImplementation((arg1, arg2))
}
}
final class StubbedMethod3[A1, A2, A3, R] extends StubbedMethod[(A1, A2, A3), R] {
def apply(arg1: A1, arg2: A2, arg3: A3): R = {
underlyingImplementation((arg1, arg2, arg3))
}
}
final class StubbedMethod4[A1, A2, A3, A4, R] extends StubbedMethod[(A1, A2, A3, A4), R] {
def apply(arg1: A1, arg2: A2, arg3: A3, arg4: A4): R = {
underlyingImplementation((arg1, arg2, arg3, arg4))
}
}
}
@ccmtaylor

Copy link
Copy Markdown

argh == arg17 in Base18 👅

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment