我在Grails 3.2.5上运行,并实现了一个简单的服务。该服务有一个私有方法和一个公共方法。私有方法触发事件的notify方法(由EventBus特征提供)。
@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)
谢谢你的帮忙!
发布于 2017-12-19 16:38:23
您可以模拟事件总线并在模拟上执行交互测试(在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
}
}
发布于 2017-02-14 08:01:04
下面的表达式:
1 * service.notify(_)
表示使用任何单个参数调用notify方法。
试试这个:
1 * service.notify(*_)
PS在“调用次数太少:”消息之后还有其他信息吗?有什么被调用的例子吗?
发布于 2017-02-15 21:35:51
为了测试事件,我发现了一种变通方法。我不是检查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
}
}
https://stackoverflow.com/questions/42215436
复制