我有一个如下事件
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
扩展方法返回一个Task/// <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));
}