0

我有以下方法:

public void Enqueue(ICommand itemToQueue)
{
    if (itemToQueue == null)
    {
        throw new ArgumentNullException("itemToQueue");
    }

    // Using the dynamic keywork to ensure the type passed in to the generic
    // method is the implementation type; not the interface.
    QueueStorage.AddToQueue((dynamic)itemToQueue);
}

QueueStorage 是实现 IQueueStorage 的依赖项。我希望对其进行单元测试,但(动态)关键字似乎阻止了 Moq 正确绑定到它。该关键字用于在添加到队列时正确分配具体类类型而不是 ICommand 接口类型。

单元测试如下所示:

[Test]
public void Enqueue_ItemGiven_AddToQueueCalledOnQueueStorage()
{
    int timesAddToQueueCalled = 0;

    var dummyQueueStorage = new Mock<IQueueStorage>();
    var testCommand = new TestCommand();

    var queueManager = new AzureCommandQueueManager();

    dummyQueueStorage
        .Setup(x => x.AddToQueue(It.IsAny<TestCommand>()))
        .Callback(() => timesAddToQueueCalled++);

    queueManager.QueueStorage = dummyQueueStorage.Object;

    queueManager.Enqueue(testCommand);

    Assert.AreEqual(1, timesAddToQueueCalled);
}

虽然测试命令是 ICommand 的空白实现:

private class TestCommand : ICommand
{
}

public interface ICommand
{
}

timesAddedToQueuCalled没有增加。我试过使用It.IsAny<ICommand>(testCommand)无济于事。看起来回调方法没有被执行。谁能看到我做错了什么?

编辑:IQueueStorage 代码:

public interface IQueueStorage
{
    void AddToQueue<T>(T item) where T : class;

    T ReadFromQueue<T>() where T : class;
}
4

1 回答 1

2

这是可以正常工作的代码:

public class AzureCommandQueueManager
{
    public void Enqueue(ICommand itemToQueue)
    {
        if (itemToQueue == null)            
            throw new ArgumentNullException("itemToQueue");

        QueueStorage.AddToQueue((dynamic)itemToQueue);
    }

    public IQueueStorage QueueStorage { get; set; }
}

public interface IQueueStorage
{
    void AddToQueue<T>(T command) where T : class;        
}

public class TestCommand : ICommand  {}

public interface ICommand {}

及测试方法:

[Test]
public void Enqueue_ItemGiven_AddToQueueCalledOnQueueStorage()
{
    int timesAddToQueueCalled = 0;

    var dummyQueueStorage = new Mock<IQueueStorage>();
    var testCommand = new TestCommand();

    var queueManager = new AzureCommandQueueManager();

    dummyQueueStorage
        .Setup(x => x.AddToQueue(It.IsAny<TestCommand>()))
        .Callback(() => timesAddToQueueCalled++);

    queueManager.QueueStorage = dummyQueueStorage.Object;

    queueManager.Enqueue(testCommand);

    Assert.AreEqual(1, timesAddToQueueCalled);
}

我看到的唯一区别 - 你有类private修饰符TestCommand。顺便说一句,如果它是私有的,您如何从测试中访问该类?

于 2012-05-16T12:47:44.363 回答