【问题标题】:Check invocation static method on Grails检查 Grails 上的调用静态方法
【发布时间】:2019-02-08 07:27:10
【问题描述】:

我有一些静态方法:

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


    【解决方案1】:

    尝试类似:

    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
    }
    

    【讨论】:

    • 我不需要替换答案,而是检查带有某些参数的调用。
    【解决方案2】:

    正确的方法是使用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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-20
      相关资源
      最近更新 更多