c# - 连接到单元测试中的事件

标签 c# unit-testing events testing event-handling

我正在尝试对一个在单独线程上执行某些操作的类运行单元测试,然后使用事件处理程序通知父级它已完成任务。这是我的测试代码:

        [TestMethod()]
    public void InitTest()
    {
        Controller target = new Controller();
        target.FinishedCommand += delegate(bool success)
        {
            Assert.AreEqual(true, success);
        };
        target.Init();
        while (true)
        {

        }
    }

这是我正在测试的方法:

public delegate void ControllerEventHandler(bool success);
public class Controller
{
    public event ControllerEventHandler FinishedCommand;
    public void Init()
    {
        FinishedCommand(true);
    }
}

我意识到 Init() 没有使用新线程,但我只是想确保测试现在正在运行。测试没有通过,而是永远卡在 while() 循环中,并且永远不会输入匿名委托(delegate)。

事件是否连接不正确?单元测试中可以这样使用事件吗?

最佳答案

Assert 不会停止测试,如果未执行 Assert 语句,测试也不会失败 - 所以 while(true)循环使您的测试无法完成。

此外,事件的行为类似于简单的方法调用 - 因此在 target.Init(); 返回之前,事件已经发生。

您可能应该使用一个变量 bool eventOccurredAndSucceeded = false,您可以在事件处理程序中设置它,并在调用 target.Init(); 后简单地测试它:

    [TestMethod()]
    public void InitTest()
    {
        bool eventOccurredAndSucceeded = false;
        Controller target = new Controller();
        target.FinishedCommand += delegate(bool success)
        {
            if (success)
            {
                eventOccurredAndSucceeded = true;
            }
        };

        target.Init();
        Assert.AreEqual(true, eventOccurredAndSucceeded);
    }

关于c# - 连接到单元测试中的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20637598/

相关文章:

python - 是否可以阻止模块/全局类变量创建单元测试实例?

java - Junit 是否会在每次调用测试方法时重新初始化类?

javascript - 为什么事件处理程序在 Firefox 中会抛出错误?

c# - 将一个值与多个可能的列表匹配进行比较

unit-testing - Qt单元测试中使用qDebug

c# - CaSTLe Windsor - 事件处理程序的注册组件

c# - ASP.Net 中的 GridView RowDeleting 事件导致的问题

c# - 在运行时更改类属性中的值

c# - 使用 C# 像写字板一样嵌入 mspaint

c# - 为什么我的 wcf 应用程序不能使用和保存 session ?