如有必要,我有一种创建队列的方法。如果队列已经存在,则如果创建成功,则该方法返回false。
[我想测试队列在QueueExists
检查期间不存在,但由另一个进程在进入CreateQueueAsync
调用之前创建的场景。
我有我的产品代码:
internal bool QueueExists(string queueName)
{
var allQueues = ManagementClient.GetQueuesAsync().Result;
if (!allQueues.Any(q => q.Path.Equals(queueName)))
{
return false;
}
return true;
}
public bool CreateQueueIfNotExists(string queueName, bool requiresSession)
{
if (!QueueExists(queueName))
{
try
{
ManagementClient.CreateQueueAsync(queueDescription).Wait();
return true;
}
catch (AggregateException ae)
{
Exception e = ae.GetBaseException();
// If the queue already exists then no additional action is needed.
if (e is MessagingEntityAlreadyExistsException)
{
return false;
}
else
{
ExceptionDispatchInfo.Throw(e);
}
}
}
else
{
return false;
}
}
我的Nunit测试CreateQueueAsync
将被调用两次,因为GetQueuesAsync
将始终返回一个空列表。
[Test]
public void QueueCreation_MessagingEntityAlreadyExistsException_IsCatched()
{
// Given
var managementClientMock = new Mock<ManagementClient>(connectionString) { CallBase = true };
managementClientMock.Setup(m => m.GetQueuesAsync(It.IsAny<int>(), It.IsAny<int>(), It.IsAny<System.Threading.CancellationToken>()))
.Returns(Task.FromResult<IList<QueueDescription>>(new List<QueueDescription>()));
QueueFactory queueFactory = new QueueFactory(managementClientMock.Object);
Assert.That(queueFactory.CreateQueueIfNotExists(alreadyExistsQueue, true), Is.True,
"First queue creation did not returned true.");
Assert.That(queueFactory.CreateQueueIfNotExists(alreadyExistsQueue, true), Is.False,
"First queue creation did not returned false.");
managementClientMock.Verify(m => m.CreateQueueAsync(It.IsAny<QueueDescription>(), It.IsAny<System.Threading.CancellationToken>()), Times.Exactly(2));
}
这很好,但是我想检查是否第二次引发并捕获了聚合异常,并且MessagingEntityAlreadyExistsException
是内部异常。因此,ExpectedException
和Assert.Throws
在这里不起作用,在乘积方法中捕获了异常。
我有没有办法用Moq做到这一点?
有趣的问题-我不知道Moq中的任何功能。但是,通过将问题分成两部分(如果我误解了,深表歉意),是否能够找到所需的内容?
首先,单独测试ManagementClient
,验证使用同一队列两次调用它会引发聚集异常,并且MessagingEntityAlreadyExistsException
是内部异常。
其次,用存根ManagementClient测试属于示例中方法的代码,该存根ManagementClient会引发一个聚合异常,该异常在调用时会包含相同的内部异常。在该测试中,请确认没有引发异常(即,该异常已被捕获且未被重新抛出)。