我希望对一个回调方法进行单元测试,该方法在对消息队列的窥视完成并且无法弄清楚如何执行此操作时调用。
我的抽象类;
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);
}
这看起来不错,但是在调用执行时,我收到一个错误,提示“'System.EventArgs' 类型的对象无法转换为'System.Messaging.PeekCompletedEventArgs'。”...而且我没有任何 AsyncResult 需要处理如果我能走到那一步。