gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:34:59 26 4
gpt4 key购买 nike

我正在编写单元测试并在尝试从抽象类模拟中引发事件时收到异常。这是示例代码:

    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.As<>()似乎是正确的方法,上面唯一的问题是事件是从 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"));

最佳答案

如果您将 mock 设为 mult-mock,则可以进行所需的转换。由于 Moq 模拟通过泛型参数绑定(bind)到单个类型,因此您必须显式地逐步向模拟添加额外的接口(interface)或父类(super class),然后在测试中使用最终产品。下面是一个如何执行此操作的简单示例。

var baseMock = new Mock<AbstractBase>();
var inpcMock = baseMock.As<INotifyPropertyChanged>();

// ...setup event...

propertyChangedMapper.Subscribe(inpcMock.Object);

// ... assertions ...

关于C# 和 Moq,从抽象类 mock 引发在接口(interface)中声明的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7474297/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com