gpt4 book ai didi

unit-testing - 在Grails上检查调用静态方法

转载 作者:行者123 更新时间:2023-12-02 15:43:07 26 4
gpt4 key购买 nike

我有一些静态方法:

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], _)
}

但是上面的代码不起作用。有合法的方法吗?

最佳答案

尝试类似的方法:

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
}

关于unit-testing - 在Grails上检查调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54587766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com