Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spock Test, only check if method is called and do not execute it

In our Spock tests we want to check if the correct path in our software is selected. But we do not want to test the function of the methods which are called (this is done in separate tests)

def "Test"() {
    setup:
    service.metaClass.innerMethod = { -> return null }

    when:
    service.doSomething("[email protected]")

    then:
    1 * service.innerMethod(*_)
}

This test always fails, because the code in the innerMethod is called and the invocations of the method calls in the innerMethod are counted and not the invocation of the method innerMethod

|  Too few invocations for:
    1 * service.innerMethod(*_)   (0 invocations)

Unmatched invocations (ordered by similarity):

    1 * secondService.doSomething()

How can I just get the invocation of innerMethod and mock the complete function away?

like image 908
Alexander Kiefer Avatar asked Mar 27 '14 08:03

Alexander Kiefer


People also ask

What does >> mean in Spock?

The right-shift ( >> ) operator defines the return value or behavior of a stubbed method.

What is stubbing in Spock?

Stubs are fake classes that come with preprogrammed return values. Mocks are fake classes that we can examine after a test has finished and see which methods were run or not. Spock makes a clear distinction between the two as mocks and stubs , as we will see in the sections to follow.


Video Answer


1 Answers

If you are not mocking the service itself, you would need to do something like this (be aware of passing the proper parameters when using metaClass:

def "Test"() {
    setup:
        def calls = 0
        service.metaClass.innerMethod = { p1 -> calls++ }
    when:
        service.doSomething("[email protected]")
    then:
        calls==1
}

and if you are mocking the service,

def "Test"() {  
    when:
        service.doSomething("[email protected]")
    then:
        1 * service.innerMethod(_)
}
like image 65
Fran García Avatar answered Oct 26 '22 23:10

Fran García