为什么界面上缺少Moq设置方法?

时间:2011-11-24 15:44:53

标签: c# dependency-injection moq

我有以下代码,它将接口传递给一个需要协议处理程序字典列表的函数:

 var _protocolHandlers = new Dictionary<EmailAccountType, IEmailTransportHandler>
                        {
                            {EmailAccountType.Pop3, new Mock<IEmailTransportHandler>().Object},
                            {EmailAccountType.IMAP, new Mock<IEmailTransportHandler>().Object}
                        };

奇怪的是,以下代码没有给我模拟对象的设置方法:

_protocolHandlers[0].<where are set-up methods??>

似乎遵循约定,将普通接口传递给服务的构造函数,因为它们接受接口,但它们是使用.Object()注入的。

有没有人知道这里发生了什么?

1 个答案:

答案 0 :(得分:5)

安装方法在Mock'容器'上,而不是传入的实际模拟对象。

如果您之前创建了模拟,您将能够访问设置然后传入对象:

[TestFixture]
public class MyTest
{        
    Dictionary<EmailAccountType, IEmailTransportHandler> _protocolHandlers;
    Mock<IEmailTransportHandler> _mockEmailTransportHander = new Mock<IEmailTransportHandler>();        

    [SetUp]
    public void Init()
    {
        _protocolHandlers = new Dictionary<EmailAccountType, IEmailTransportHandler>
                    {
                        {EmailAccountType.Pop3, _mockEmailTransportHander.Object},
                        {EmailAccountType.IMAP, _mockEmailTransportHander.Object} 
                    };
    }

    [Test]
    public void Test1() 
    {
        _mockEmailTransportHander.Setup(m => m.Test()).Returns(false);
        // Rest of test
    }

    [Test]
    public void Test2() 
    {
        _mockEmailTransportHander.Setup(m => m.Test()).Returns(true);
        // Rest of test
    }
}