Reputation: 1076
How can I mock dependend traits with mockito? I have two traits:
trait A {
def a = 1
}
trait B extends A {
def b = {
// do things
a
// do things
}
}
Now, I want to test Trait B. And I want to verify, that A.a() gets called:
class SmallTest extends FunSuite with MockitoSugar {
test("prove, that a gets called") {
val mockA = mock[A]
val b = new B with mockA {} // This won't compile
b.b
verify(mockA).a
}
}
This example won't compile. But how would I "inject" my mock otherwise?
Upvotes: 3
Views: 3553
Reputation: 2824
Using spy would be a better choice. mockito spy
// the class being spied cannot be final,
// so we cannot do this:
// spy(new B {})
class C extends B
val c = spy(new C)
c.b
verify(c).a
Upvotes: 1
Reputation: 1076
Ok, found a way. This will work. Maybe a bit unhandy, if there are a lot methods, I have to override... In this example I added method parameters to the method I want to mock, to show the repetition, which doesn't look very nice.
trait A {
def a(i: Int) = i + 1
}
trait B extends A {
def b(j: Int) = {
// do things
a(j)
// do things
}
}
test("prove, that a gets called") {
val mockA = mock[A]
val b = new B {
override def a(j: Int) = mockA.a(j)
}
b.b(1)
verify(mockA).a(1)
}
Upvotes: 1