C#和Moq,引发在抽象类mock的接口中声明的事件

前端之家收集整理的这篇文章主要介绍了C#和Moq,引发在抽象类mock的接口中声明的事件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在编写单元测试并在尝试从抽象类mock中引发事件时收到异常.以下是示例代码
public abstract class AbstractBase : EntityObject
    {}

    [TestMethod]
    public void MyTest()
    {

        var mock = new Mock<AbstractBase>();
        var notificationMock = entityMock.As<INotifyPropertyChanged>();

        var propertyChangedMapper = new PropertyChangedMapper();

        bool eventReceived = false;
        propertyChangedMapper.MyPropertyChanged +=
            (sender,eventArgs) =>
                {
                    eventReceived = true;
                };

        propertyChangedMapper.Subscribe((AbstractBase)notificationMock.Object);

        Assert.IsFalse(eventReceived);

        notificationMock.Raise(e=>e.PropertyChanged += null,new PropertyChangedEventArgs("Property1"));

        Assert.IsTrue(eventReceived);
  }

显然我可以在INotifyPropertyChanged上使用mock并且事件上升很好,但是在PropertyChangedMapper中我需要将发送者强制转换为AbstractBase,如果使用Mock< INotifyPropertyChanged>

编辑:
根据使用Mock的建议.由于<>()似乎是正确的方法,上面唯一的问题是从notificationMock上升的事件与对象的原始模拟无关.码:

notificationMock.Object.PropertyChanged += (s,e) =>
        {
            var result = "this one is fired as it should";
        };

        mock.Object.PropertyChanged += (s,e) =>
        {
            var result = "this one is not called but is actually what I need";
        }; 

        notificationMock.Raise(e => e.PropertyChanged += null,new PropertyChangedEventArgs("Property1"));

解决方法

如果你让你的模拟成为一个多模拟,你可以做所需的演员表.由于Moq模拟通过泛型参数绑定到单个类型,因此必须显式逐步向模拟中添加其他接口或超类,然后在测试中使用最终产品.下面是一个如何执行此操作的简单示例.
var baseMock = new Mock<AbstractBase>();
var inpcMock = baseMock.As<INotifyPropertyChanged>();

// ...setup event...

propertyChangedMapper.Subscribe(inpcMock.Object);

// ... assertions ...

猜你在找的C#相关文章