首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在C#中(按顺序)引发事件的单元测试

在C#中(按顺序)引发事件的单元测试
EN

Stack Overflow用户
提问于 2008-10-30 01:21:41
回答 5查看 88.4K关注 0票数 166

我有一些引发PropertyChanged事件的代码,我希望能够单元测试事件是否被正确引发。

引发事件的代码如下所示

public class MyClass : INotifyPropertyChanged
{
   public event PropertyChangedEventHandler PropertyChanged;  

   protected void NotifyPropertyChanged(String info)
   {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
   }  

   public string MyProperty
   {
       set
       {
           if (_myProperty != value)
           {
               _myProperty = value;
               NotifyPropertyChanged("MyProperty");
           }
       }
   }
}

在我的单元测试中,我从使用委托的以下代码中得到了一个不错的绿色测试:

[TestMethod]
public void Test_ThatMyEventIsRaised()
{
    string actual = null;
    MyClass myClass = new MyClass();

    myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
    {
         actual = e.PropertyName;
    };

    myClass.MyProperty = "testing";
    Assert.IsNotNull(actual);
    Assert.AreEqual("MyProperty", actual);
}

但是,如果我尝试将属性的设置链接在一起,如下所示:

public string MyProperty
{
    set
    {
        if (_myProperty != value)
        {
            _myProperty = value;
            NotifyPropertyChanged("MyProperty");
            MyOtherProperty = "SomeValue";
        }
    }
}

public string MyOtherProperty
{
    set
    {
        if (_myOtherProperty != value)
        {
            _myOtherProperty = value;
            NotifyPropertyChanged("MyOtherProperty");
        }
    }
}

我对事件的测试失败了-它捕获的事件是MyOtherProperty的事件。

我非常确定事件会触发,我的UI会做出类似的反应,但我的委托只会捕获要触发的最后一个事件。

所以我想知道:

我测试事件的方法正确吗?引发链接事件的方法正确吗?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/248989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档