单元测试在查看完成时使用的异步回调方法

时间:2012-09-24 09:48:48

标签: c# moq mstest msmq

我希望单元测试在查看消息队列时查看的回调方法,并且无法弄清楚如何执行此操作。

我的抽象类;

public abstract class QueueHandler : WindowsServiceBase
{
    private readonly IMessageQueueWrapper _listeningQueue;
    private PeekCompletedEventHandler _peekHandler;

    protected QueueHandler(IMessageQueueWrapper listeningQueue) 
        : base()
    {
        _listeningQueue = listeningQueue;
    }

    protected override void ExecuteInternal()
    {
        _listeningQueue.BeginPeek();
    }

    protected override void ConfigureInternal()
    {
        if (_peekHandler != null) return;

        _peekHandler = OnPeekCompleted;
        _listeningQueue.PeekCompleted += OnPeekCompleted;
    }

    protected void OnPeekCompleted(object sender, PeekCompletedEventArgs e)
    {
        try
        {
            var msg = _listeningQueue.EndPeek(e.AsyncResult);

            ...
        }
        catch (Exception ex)
        {
            ...
        }
    }
}

我用于单元测试的具体课程;

internal class QueueuHandlerImplementation : QueueHandler
{
    public QueueuHandlerImplementation(IMessageQueueWrapper listeningQueue)
        : base(listeningQueue)
    {
    }
}

我的单元测试;

public void OnPeekCompletedWhenBeginPeekShouldCallOnPeekCompleted()
{
        QueueuHandlerImplementation queueHandler = new QueueuHandlerImplementation(_listeningQueueMock.Object);

    //Arrange
    queueHandler.Configure();
    _listeningQueueMock.Setup(m => m.BeginPeek()).Raises(
                    m => m.PeekCompleted += null, new PeekCompletedEventArgs() { AsyncResult = new Mock<IAsyncResult>().Object});

    //Act
    _queueHandler.Execute();

    //Assert
    Assert.AreEqual(true, _queueHandler.IsConfigured);
}

这是不可能的,因为PeekCompletedEventArgs没有默认构造函数。

public void OnPeekCompletedWhenBeginPeekShouldCallOnPeekCompleted()
{
        QueueuHandlerImplementation queueHandler = new QueueuHandlerImplementation(_listeningQueueMock.Object);

    //Arrange
    queueHandler.Configure();
    _listeningQueueMock.Setup(m => m.BeginPeek()).Raises(
                m => m.PeekCompleted += null, PeekCompletedEventArgs.Empty);

    //Act
    _queueHandler.Execute();

    //Assert
    Assert.AreEqual(true, _queueHandler.IsConfigured);
}

这看起来很不错但是在调用execute时我得到一个错误,上面写着对象类型&#34;&#39; System.EventArgs&#39;无法转换为类型&#39; System.Messaging.PeekCompletedEventArgs&#39;。&#34; ...如果我能做到这一点,我没有任何AsyncResult可以照顾。

1 个答案:

答案 0 :(得分:2)

您可以使用内部构造函数创建实例:

MessageQueue sender = null;
IAsyncResult result = null;
var e = Activator.CreateInstance(typeof(System.Messaging.PeekCompletedEventArgs),
                                 BindingFlags.NonPublic | BindingFlags.Instance,
                                 null, new object[]{sender, result}, null);

注意:当您访问sender属性时,nullMessage这一事实将导致NullReferenceException。