moq验证PublishOnUIThreadAsync异步方法

moq验证PublishOnUIThreadAsync异步方法

本文介绍了Caliburn EventAggregator moq验证PublishOnUIThreadAsync异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下活动

namespace MyProject
{
    public class MyEvent
    {
        public MyEvent(int favoriteNumber)
        {
            this.FavoriteNumber = favoriteNumber;
        }

        public int FavoriteNumber { get; private set; }
    }
}

我有一个引发此事件的方法.

And I have a method which raises this event.

using Caliburn.Micro;
//please assume the rest like initializing etc.
namespace MyProject
{
    private IEventAggregator eventAggregator;

    public void Navigate()
    {
        eventAggregator.PublishOnUIThreadAsync(new MyEvent(5));
    }
}

如果我仅使用PublishOnUIThread,则下面的代码(在单元测试中)可以正常工作.

If I using just PublishOnUIThread, the below code (in an unit test) is working fine.

eventAggregatorMock.Verify(item => item.Publish(It.IsAny<MyEvent>(), Execute.OnUIThread), Times.Once);

但是如何检查相同版本的异步版本?

But how do I check for async version for the same?

eventAggregatorMock.Verify(item => item.Publish(It.IsAny<MyEvent>(), Execute.OnUIThreadAsync), Times.Once);

在验证异步方法时遇到麻烦.假设private Mock<IEventAggregator> eventAggregatorMock;. Execute.OnUIThreadAsync部分给出错误'Task Execute.OnUIThreadAsync' has the wrong return type.

Facing trouble verifying the async method. Assume private Mock<IEventAggregator> eventAggregatorMock;. The part Execute.OnUIThreadAsync gives error 'Task Execute.OnUIThreadAsync' has the wrong return type.

我也尝试过

eventAggregatorMock.Verify(item => item.Publish(It.IsAny<MyEvent>(), action => Execute.OnUIThreadAsync(action)), Times.Once);

但是说,System.NotSupportedException: Unsupported expression: action => action.OnUIThreadAsync()

谢谢.

推荐答案

IEvenAggregator.Publish定义为

void Publish(object message, Action<System.Action> marshal);

因此,您需要提供适当的表达式以匹配该定义.

Therefore you would need to provide a proper expression to match that definition.

eventAggregatorMock.Verify(_ => _.Publish(It.IsAny<MyEvent>(),
                                It.IsAny<Action<System.Action>>()), Times.Once);

PublishOnUIThreadAsync扩展方法还返回任务

/// <summary>
/// Publishes a message on the UI thread asynchrone.
/// </summary>
/// <param name="eventAggregator">The event aggregator.</param>
/// <param name="message">The message instance.</param>
public static Task PublishOnUIThreadAsync(this IEventAggregator eventAggregator, object message) {
    Task task = null;
    eventAggregator.Publish(message, action => task = action.OnUIThreadAsync());
    return task;
}

所以应该等待

public async Task Navigate() {
    await eventAggregator.PublishOnUIThreadAsync(new MyEvent(5));
}

这篇关于Caliburn EventAggregator moq验证PublishOnUIThreadAsync异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:58