Search code examples
unit-testinggrailsstatic

Check invocation static method on Grails


I have some static method:

class WebUtils {
    static httpPostRequest(String url, Map data, Map headers) {
        //some code here
    }
}

And service:

class ChatService {
    void sendMessage(String text) {
        //some preparing code
        WebUtils.httpPostRequest(url, data, headers)
    } 
}

Now I want to check invocation of static method in the service by unit-test. Somehow like this:

void "test sending message"() {
    given:
        String text = 'Test'
        def mockedWebUtils = Mock(WebUtils)

    when:
        service.sendMessage(message)

    then:
        1*mockedWebUtils.httpPostRequest(_, [text: message], _)
}

But code above is not working. Is there legal way?


Solution

  • The correct way is using GroovyMock instead Mock:

    void "test sending message"() {
        given:
            String text = 'Test'
            GroovyMock(global:true, WebUtils)
    
        when:
            service.sendMessage(text)
    
        then:
            1*WebUtils.httpPostRequest(_, [text: text], _)
    }
    

    I've found here:http://spockframework.org/spock/docs/1.3-RC1/interaction_based_testing.html#_mocking_static_methods