代码之家  ›  专栏  ›  技术社区  ›  Hussain Mir

Caliburn EventAggregator moq verify PublishOnUIThreadAsync异步方法

  •  3
  • Hussain Mir  · 技术社区  · 7 年前

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

    提前谢谢。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Nkosi    7 年前

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