Can Spock spy for real object?
Asked Answered
H

2

6

I wanna spy method calls of Spring bean. I checked docs - Spock can create spy only by constructor. Can Spock wrap already existing object by spy?

Howdoyoudo answered 6/2, 2015 at 15:42 Comment(1)
If I'm not mistaken you can't do this because it creates a proxy, i.e., it creates a derived type on the fly.Barely
S
3

It seems that it can't be done because of the fact that API doesn't support it. Have a look at API. The following piece of code runs with errors:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')

import spock.lang.*

class Test extends Specification {
    def 'test'() {
        given:    
        def o = new Object()
        def s = Spy(o)
    }
}
Synaeresis answered 6/2, 2015 at 17:45 Comment(2)
This may no longer be the case. From the 1.1 release notes: "You may also create a spy from an instantiated object. This may be useful in cases where you do not have full control over the instatiation of types you are interested in spying. (For example when testing within a Dependency Injection framework such as Spring or Guice.)"Fanfani
For creating a spy from an instantiated object like @StefanvandenAkker quoted^, if anyone can post an example, thank you.Afterbirth
D
2

From the official Spock framework documentation:

You may also create a spy from an instantiated object. This may be useful in cases where you do not have full control over the instatiation of types you are interested in spying. (For example when testing within a Dependency Injection framework such as Spring or Guice.)

Daystar answered 21/8, 2020 at 11:49 Comment(1)
If anyone can post an example, thank you.Afterbirth

© 2022 - 2024 — McMap. All rights reserved.