Unit testing that events are raised in C# (in order)

前端 未结 7 2306
小蘑菇
小蘑菇 2020-11-29 16:02

I have some code that raises PropertyChanged events and I would like to be able to unit test that the events are being raised correctly.

The code that i

7条回答
  •  鱼传尺愫
    2020-11-29 16:45

    Based on this article, i have created this simple assertion helper :

    private void AssertPropertyChanged(T instance, Action actionPropertySetter, string expectedPropertyName) where T : INotifyPropertyChanged
        {
            string actual = null;
            instance.PropertyChanged += delegate (object sender, PropertyChangedEventArgs e)
            {
                actual = e.PropertyName;
            };
            actionPropertySetter.Invoke(instance);
            Assert.IsNotNull(actual);
            Assert.AreEqual(propertyName, actual);
        }
    

    With this method helper, the test becomes really simple.

    [TestMethod()]
    public void Event_UserName_PropertyChangedWillBeFired()
    {
        var user = new User();
        AssertPropertyChanged(user, (x) => x.UserName = "Bob", "UserName");
    }
    

提交回复
热议问题