.net - Caliburn EventAggregator moq 验证 PublishOnUIThreadAsync 异步方法

标签 .net unit-testing asynchronous moq caliburn.micro

我有一个事件如下

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

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

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

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

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

如果我只使用 PublishOnUIThread,下面的代码(在单元测试中)工作正常。

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

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

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 .

我也尝试过

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);

因此,您需要提供正确的表达式来匹配该定义。

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));
}

关于.net - Caliburn EventAggregator moq 验证 PublishOnUIThreadAsync 异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45954868/

相关文章:

unit-testing - 了解Grails的mockFor需求

javascript - 使用 sinon 提交表单时如何测试函数是否被调用?

c# - Async WebClient 不是真正的异步?

java - 等待 onPostExecute 完成以制作新的适配器

c# - 在断开连接时关闭客户端套接字

c# - 读/写锁定混淆

.net - asp :GridView textbox always return blank value

c# - 等待使用 AutoResetEvent 处理事件

javascript - AngularJS 单元测试 - 未定义不是函数

c# - Active Directory RoleProvider -Principal.IsMemberOf 抛出PrincipalOperationException