gpt4 book ai didi

c# - 验证已执行的事件处理程序代码

转载 作者:行者123 更新时间:2023-11-30 18:01:10 26 4
gpt4 key购买 nike

我有与此非常相似的代码,但不知道如何测试事件处理程序是否发生。

public class MyClass : MyAbstractClass
{
IFileSystem FileSystem;

public MyClass(IFileSystem myFileSys)
{
FileSystem = myFileSys;
FileSystem.EventHit += new EventHandler(FileSystem_EventHit);
}

public void FileSystem_EventHit(object sender, EventArgs e)
{
//Testing base.OnOutput is not possible which I wont go into
base.OnOutput("EventHit");
}
}

测试代码在这里:

    [Test]
public void DoSomething_WhenCalled_EventFired()
{
var mock = new Moq.Mock<IFileSystem>();

MyClass plugin = new MyClass (mock.Object);

mock.Object.DoSomething();

mock.Raise(x => x.EventHit += null, new EventArgs());

//Verify/Assert that MyClass handled and did something in the event handler

}

最佳答案

我能想到的最简单的方法是在测试方法中添加您自己的处理程序,我认为这应该足够了吗?

[Test]
public void DoSomething_WhenCalled_EventFired()
{
var mock = new Moq.Mock<IFileSystem>();
bool isHit = false;

mock.EventHit += (s, e) =>
{
isHit = true;
};

MyClass plugin = new MyClass (mock.Object);

mock.Object.DoSomething();

mock.Raise(x => x.EventHit += null, new EventArgs());

Assert.IsTrue(isHit);

}

关于c# - 验证已执行的事件处理程序代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9362045/

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