Dislaimer: there was a question that might look similar, but it's actually different: Mocking a Superclass in Spock
Ex:
class Bar {
def method(){
return 'bar'
}
}
class Foo extends Bar {
def method() {
super.method() + ' foo'
}
}
I want to test Foo
in isolation, i.e. I want to mock Bar
, like:
def "test"() {
given:
def foo = GroovySpy(Foo)
when:
def result = foo.method()
then:
1 * ((Bar) directive).generate() >> 'mockBar'
result == 'mockBar foo'
}
This obviously won't work, but gives the idea what I'm trying to achieve. Any ideas?
Just an idea if you want to mock only Bar.method()
:
class Foo extends Bar {
def superMethod() {
super.method()
}
def method() {
superMethod() + ' foo'
}
}
Your test:
def "test"() {
given:
def foo = new Foo() {
@Override
def superMethod() {
'mockBar'
}
}
expect:
foo.method() == 'mockBar foo'
}
I just found out how to do this.
I put there the following:
then:
1 * foo.method()
0 * foo._
It gave me exact method that has been called after what I call from when:
, and I put it like this:
then:
1 * foo.super$3$method()
I'm not sure from where $3$
is coming from, maybe that's the inheritance level or something, I think if you try this out you might have different numbers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With