递归模拟 Outlook.Interop 接口与最小起订量抛出 "Invalid Operation Exception"

Recursive mocking Outlook.Interop interface with Moq throws "Invalid Operation Exception"

我尝试测试我的 Outlook 加载项,但我在模拟对象时遇到问题。 我正在使用 Moq,我想测试收件人的数量是否为 0。 这是代码:

[TestMethod]      
[ExpectedException(typeof(ArgumentException))]
public void CheckValidMail_ZeroRecipientens()
{                  
    var mock = new Mock<Microsoft.Office.Interop.Outlook.MailItem>();
    //In this line i get the Exception
    mock.Setup(b => b.Recipients.Count).Returns(0);
    // I also tried this one
    //mock.SetupProperty(x => x.Recipients.Count, 0);         
    var  t = mock.Object;               
    var mailconverter = new MailConverter(t);          
    mailconverter.CheckValidMail();

}

然后我得到这个异常:

System.InvalidOperationException: "The variable" x "of type" Microsoft.Office.Interop.Outlook.MailItem "is referenced by the range" ", but it is not defined."

这是MailconverterClass

public class MailConverter
{
    private Outlook.MailItem mail;

    public MailConverter(Outlook.MailItem mailItem)
    {
        this.mail = mailItem;
    }

    public void CheckValidMail()
    {
        CheckRecipientsCount();            
    }

    private void CheckRecipientsCount()
    {
        if (mail.Recipients.Count == 0) 
            throw new ArgumentException("Min 1 Recipient");
        else if (mail.Recipients.Count > 1)
            throw new ArgumentException("Max 1 Recipient");
    }
}

我做错了什么?

在查找具有类似错误消息的帖子后,该错误似乎与 lambda 表达式 creation/construction 期间的参数名称冲突有关。

我认为这与尝试递归模拟

设置的框架有关
mock.Setup(b => b.Recipients.Count).Returns(0);

模拟框架无法递归模拟 Count 属性,因为它在包装 Recipients 属性.

时与某些东西发生冲突

我不确定问题是否源于互操作接口本身,但在测试时分别模拟每个接口都有效。

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void CheckValidMail_ZeroRecipientens() {
    //Arrange
    var mockRecpients = new Mock<Microsoft.Office.Interop.Outlook.Recipients>();
    mockRecpients.Setup(_ => _.Count).Returns(0);
    var mockMailItem = new Mock<Microsoft.Office.Interop.Outlook.MailItem>();
    mockMailItem.Setup(_ => _.Recipients).Returns(mockRecpients.Object);
    var mailItem = mockMailItem.Object;
    var mailconverter = new MailConverter(mailItem);

    //Act
    mailconverter.CheckValidMail();
}