2017-08-30 126 views
1

我有一个事件如下卡利EventAggregator MOQ验证PublishOnUIThreadAsync异步方法

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

在此先感谢。

回答

0

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

仅供参考,它的工作,而无需修改方法为你规定。如果我试图“等待”它,我得到'System.NullReferenceException:对象引用未设置为对象的实例。' –

+0

@HussainMir这是因为没有设置将返回任务,因此它是空的。 https://github.com/Caliburn-Micro/Caliburn.Micro/blob/master/src/Caliburn.Micro/Execute.cs#L30 – Nkosi

+0

嗨,我试过这个'MyEvent navigateEvent = null; eventAggregatorMock.Setup(x => x.Publish(It.IsAny (),It.IsAny >()))。回调>((t,s )=> navigateEvent =(MyEvent)t);'但测试仍然失败。有关如何设置的任何提示? –