【发布时间】:2012-02-23 15:02:01
【问题描述】:
我有一个服务,它使用 jms-grails 插件提供的 sendJMSMessage 方法。 我想写一些单元测试,但我不确定如何“模拟”这个方法,所以它什么都不做。 有什么建议吗?
【问题讨论】:
标签: unit-testing testing grails plugins
我有一个服务,它使用 jms-grails 插件提供的 sendJMSMessage 方法。 我想写一些单元测试,但我不确定如何“模拟”这个方法,所以它什么都不做。 有什么建议吗?
【问题讨论】:
标签: unit-testing testing grails plugins
你可以对方法进行元分类,让它返回你想要的任何东西。
@Test
void pluginCode() {
def myService = new MyService()
def wasCalled = false
myService.metaClass.sendJMSMessage = {String message ->
//I like to have an assert in here to test what's being passed in so I can ensure wiring is correct
wasCalled = true
null //this is what the method will now return
}
def results = myService.myServiceMethodThatCallsPlugin()
assert wasCalled
}
当我从 metaClassed 方法返回 null 时,我喜欢有一个 wasCalled 标志,因为我不特别喜欢断言响应是 null,因为它并不能真正保证你是正确接线。如果您要返回某种独特的东西,尽管您可以不使用 wasCalled 标志。
在上面的示例中,我使用了 1 个字符串参数,但您可以 metaClass 输出任意数量/类型的参数来匹配实际发生的情况。
【讨论】: