fuzzycuffs
fuzzycuffs

Reputation: 139

ScalaMock Stubbing with default parameters

I'm trying to mock a function like

def foo(x: A, y: B, z: C = blah)

where blah is a java connection object that I don't want to create on the spot

However when I try to stub it like

    (object.foo _)
  .stubs(a, b)

It errors out and says overloaded method value stubs with alternatives... because it's looking for the third parameter. Is there anyway to get around this.

Upvotes: 0

Views: 1772

Answers (2)

Philipp
Philipp

Reputation: 967

I agree with Matt, but want to point out there is a wildcard syntax in ScalaMock (*) - http://scalamock.org/user-guide/matching/

trait Foo {
  def foo(x: Int, y: Int, z: Int = 0): Int
}

val a: Int = ???
val b: Int = ???
val m = mock[Foo]

m.foo _ stubs(a, b, *)

Upvotes: 4

Matt Fowler
Matt Fowler

Reputation: 2733

You can use a wildcard when you're stubbing out your method.

The following test passes and I think is what you're looking for:

class DefaultParameterTest extends FlatSpec with Matchers with MockFactory {

  class A {
    def foo(x: Int, y: Int, z: Int = 0): Int = 0
  }

  it should "work with a default parameter" in {
    val bar = mock[A]
    (bar.foo _).stubs(1, 2, _: Int).returning(5)

    bar.foo _ expects(1, 2, 0) returning 5 once()

    bar.foo(1, 2)
  }

}

Upvotes: 0

Related Questions