unit testing - Mock static method with GroovyMock or similar in Spock -
first-timer here, apologies if i've missed anything. i'm hoping around call static method using spock. feedback great
with groovy mocks, thought i'd able past static call haven't found it. background, i'm in process of retrofitting tests in legacy java. refactoring prohibited. i'm using spock-0.7 groovy-1.8.
the call static method chained instance call in form:
public class classundertest{ public void methodundertest(parameter param){ //everything else commented out thing = classwithstatic.staticmethodthatreturnsaninstance().instancemethod(param); } }
staticmethod returns instance of classwithstatic instancemethod returns thing needed in rest of method
if directly exercise global mock, returns mocked instance ok:
def exercisethestaticmock(){ given: def globalmock = groovymock(classwithstatic,global: true) def instancemock = mock(classwithstatic) when: println(classwithstatic.staticmethodthatreturnsaninstance().instancemethod(testparam)) then: interaction{ 1 * classwithstatic.staticmethodthatreturnsaninstance() >> instancemock 1 * instancemock.instancemethod(_) >> returnthing } }
but if run methodundertest classundertest:
def failingattempttogetpaststatic(){ given: def globalmock = groovymock(classwithstatic,global: true) def instancemock = mock(classwithstatic) classundertest myclassundertest = new classundertest() when: myclassundertest.methodundertest(testparam) then: interaction{ 1 * classwithstatic.staticmethodthatreturnsaninstance() >> instancemock 1 * instancemock.instancemethod(_) >> returnthing } }
it throws down real instance of classwithstatic goes on fail in instancemethod.
spock can mock static methods implemented in groovy. mocking static methods implemented in java, you'll need use tool groovymock , powermock or jmockit.
ps: given these tools pull of deep tricks in order achieve goals, i'd interested hear if , how work tests implemented in groovy/spock (rather java/junit).
Comments
Post a Comment