Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking super#method() in Spock

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?

like image 363
Dee Avatar asked Oct 15 '25 18:10

Dee


2 Answers

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'
}
like image 200
Dmytro Maslenko Avatar answered Oct 17 '25 09:10

Dmytro Maslenko


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.

like image 22
Dee Avatar answered Oct 17 '25 09:10

Dee