接口指定对象的起订量 属性

Moq property of an object specified by an Interface

有没有办法对接口公开的对象起订 属性?

拥有:

interface IMyInterface {
   CurrentContact CurrentContact { get; }
}

联系人 class 有一个字段 "BirtDate" 在代码中的某处使用,因此需要被模拟

public class CurrentContact : ContactEntity
  {
    public IEnumerable<CustomerAddress> ContactAddresses { get; }
    public Organization ContactOrganization { get; }
...

我也是:

customerContextMock = new Mock<IMyInterface>();
customerContextMock.Setup(x => x.CurrentContact.BirthDate)
                .Returns(new CustomerContact {BirthDate = DateTime.MaxValue}.BirthDate);

但是我收到以下错误

Additional information: Invalid setup on a non-virtual (overridable in VB) member: x => x.CurrentContact.BirthDate

有没有在不添加这个(和任何其他字段)的情况下模拟这个我需要最小起订量到 IMyInterface 作为属性?

我建议在您的代码中创建一个接口 IContact,其中包含您需要的来自第三方 Contact class 的所有属性。然后使用 Adapter Pattern 连接到 Contact class。最后你可以模拟整个 IContact 界面。这种方法还有一个很大的优势,即在整个应用程序中你独立于第三方 Contact class 除了在接触适配器 class.

更详细地说,这可能看起来像这样:

public interface IMyInterface
{
  IContact CurrentContact { get; }
}

public interface IContact
{
  DateTime BirthDate { get; }
  // define more needed properties here
}

public class ContactAdapter : IContact
{
  private readonly Contact _contact;

  public ContactAdapter(Contact contact)
  {
    _contact = contact;
  }

  public DateTime BirthDate
  {
    get { return _contact.BirthDate; }
  }

  // delegate more properties to third party Contact class
}

所以你可以用这样的东西模拟整个 IContact 例如:

var contactMock = new Mock<IContact>();
contactMock.Setup(c => c.BirthDate).Returns(DateTime.MaxValue);

作为最后一步,您必须连接 IContact 接口以在生产代码中使用 ContactAdapter。正如您在上面看到的,ContactAdapter 获取第三方 Contact class 作为构造函数参数。 理想情况下,您会使用 IoC 容器来设置接线。