单元测试事件处理程序

时间:2012-03-21 04:29:03

标签: c# events testing handler

我有这个事件句柄,我该如何进行单元测试

public class MyLearningEvent
{
    private event EventHandler _Closed;

    public event EventHandler Closed
    {
        add
        {
            _Closed -= value;
            _Closed += value;
        }
        remove
        {
            _Closed -= value;
        }
    }

    public void OnClosed()
    {
        if (_Closed != null) _Closed(this, EventArgs.Empty);
    }
}

修改代码以便更清楚

由于

2 个答案:

答案 0 :(得分:2)

您不应该对该代码进行单元测试。它是.NET内置的一项功能。你的事件处理是有缺陷的imho。

add
{
    _Closed -= value;
    _Closed += value;
}

可能意味着您的订阅者不会跟踪他们是否已订阅。这可能导致内存泄漏:http://blog.naviso.fr/wordpress/wp-content/uploads/2011/11/MemoryLeaks-English.jpg

更健壮(和线程安全的实现)是:

public class MyLearningEvent
{
    public event EventHandler Closed = delegate {};

    public void TriggerClosed()
    {
        Closed(this, EventArgs.Empty);
    }
}

但你不应该让其他人触发该事件(使TriggerClosed私有/受保护)

答案 1 :(得分:0)

试试这个方法。这假设MyClass.Close()引发了MyClass.Closed事件。

public void ClosedEventHandlerIsNotCalledAfterBeingRemoved()
{
    MyLearningEvent Target = new MyLearningEvent();
    EventHandler Target_Closed = new EventHandler((sender, e) => { Assert.Fail("Closed EventHandler was raised after being removed."); });
    Target.Closed += Target_Closed;
    Target.Closed -= Target_Closed;
    Target.OnClosed();
}