且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为触发的事件编写单元测试?

更新时间:2023-02-16 23:07:01

你好,



您可以在单元测试中使用代表来完成。



例如:



Hello,

You could do it using delegates in your unit tests.

for example:

[TestMethod]
public void EventShouldBeRaised()
{
    ClassToTest classToTest = new ClassToTest();
    bool eventRaised = false;

    classToTest.EventRaised += delegate(object sender, ClassToTestEventArgs e)
    {
        eventRaised = true;
    };

    classToTest.Property1 = "somthing";
    // this property raises an event, test if the boolean is set to true in the delegate call.
    Assert.AreEqual(eventRaised, true);
}

[TestMethod]
public void EventShouldNotBeRaised()
{
    ClassToTest classToTest = new ClassToTest();
    bool eventRaised = false;

    classToTest.EventRaised += delegate(object sender, ClassToTestEventArgs e)
    {
        eventRaised = true;
    };

    classToTest.AnotherProperty = "somthing";
    // This property does not raise the event, so we test that the eventRaised boolean is false.
    Assert.AreEqual(eventRaised, false);
}





Valery。



Valery.