检查调用上Grails的静态方法

问题描述 投票:0回答:2

我有一些静态方法:

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

和服务:

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

现在我想通过单元测试,以检查静态方法调用的服务。不知怎的,像这样:

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

    when:
        service.sendMessage(message)

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

但上面的代码是行不通的。是否有合法的方式?

unit-testing grails static
2个回答
0
投票

尝试是这样的:

void "test sending message"() {
    given:
        WebUtils.metaClass.static.httpPostRequest = { String url, Map data, Map headers ->
            return 'done' // you can do what you want here, just returning a string as example
        }
    when:
        service.sendMessage( 'Test' )
    then:
        1
        // test for something your method has done
}

0
投票

正确的方法是使用GroovyMock代替Mock

void "test sending message"() {
    given:
        String text = 'Test'
        GroovyMock(global:true, WebUtils)

    when:
        service.sendMessage(text)

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

我在这里找到:http://spockframework.org/spock/docs/1.3-RC1/interaction_based_testing.html#_mocking_static_methods

© www.soinside.com 2019 - 2024. All rights reserved.