【问题标题】:How to test the triggering of an event in a service in Grails 3.2?如何在 Grails 3.2 中测试服务中事件的触发?
【发布时间】:2017-02-13 23:35:56
【问题描述】:

我在 Grails 3.2.5 上运行并实现了一个简单的服务。该服务有一个私有方法和一个公共方法。私有方法触发 EventBus 的 notify 方法(由 Events trait 提供)。

@Transactional
class SyncService {
    def processQueue() {
        checkStatus(true)
    }

    private checkStatus(status) {
       if(status) {
           def model = [...]
           notify "status.completed", model
       }
    }
}

如何为此服务编写单元测试,检查通知是否已触发?以下实现不起作用:

@TestFor(SyncService)
class SyncServiceSpec extends Specification {

    void "test if notification is triggerd() {
        when:
            service.processQueue()

        then: "notification should be triggered"
            1 * service.notify(_)

    }
}

测试失败,输出如下:

Too few invocations for:

1 * service.notify(_)   (0 invocations)

感谢您的帮助!

【问题讨论】:

    标签: events grails spock


    【解决方案1】:

    您可以模拟事件总线并在模拟上执行交互测试(在 3.2.11 中测试)

    @TestFor(SyncService)
    class SyncServiceSpec extends Specification {
    
      void 'test if notification is triggered'() {
        given: 'a mocked event bus'
        EventBus eventBusMock = Mock(EventBus)
        service.eventBus = eventBusMock
    
        when:
        service.processQueue()
    
        then: 'event bus is notified once'
        1 * eventBusMock.notify(*_)  //<--- you could get more specific with your arguments if you want
    
      }
    }
    

    【讨论】:

    • 是否应将 then 子句改为指定 1 * service.eventBus.notify(*_)?
    • 此外,这似乎引发了groovy.lang.ReadOnlyPropertyException 异常。
    【解决方案2】:

    下面的表达式:

    1 * service.notify(_)
    

    表示使用任何单个参数对 notify 方法的单个调用。

    试试这个:

    1 * service.notify(*_)
    

    PS 在“Tooless invocations for:”消息之后是否有任何其他信息?有什么调用的例子吗?

    【讨论】:

    • 感谢您的建议!我已经尝试过了,但仍然收到相同的消息。是的,还有一个附加信息表明方法 processQueue 已被调用一次。就是这样。
    【解决方案3】:

    我发现了一种解决方法来测试该事件。我没有检查是否触发了 notify 方法,而是使用 on 方法测试事件是否被触发。因此,在我的测试课中,我有类似的东西:

    @TestFor(SyncService)
    class SyncServiceSpec extends Specification {
    
        void "test if notification is triggerd() {
            when:
                def eventResponse = null
                service.processQueue()
                service.on('status.completed') { data ->
                    eventResponse = data
                }
    
    
            then: "notification should be triggered"
                eventResponse != null
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 2015-04-17
      相关资源
      最近更新 更多