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

前端 未结 7 2186
小蘑菇
小蘑菇 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:54

    Below is a slightly changed Andrew's code which instead of just logging the sequence of raised events rather counts how many times a specific event has been called. Although it is based on his code I find it more useful in my tests.

    [TestMethod]
    public void Test_ThatMyEventIsRaised()
    {
        Dictionary<string, int> receivedEvents = new Dictionary<string, int>();
        MyClass myClass = new MyClass();
    
        myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
        {
            if (receivedEvents.ContainsKey(e.PropertyName))
                receivedEvents[e.PropertyName]++;
            else
                receivedEvents.Add(e.PropertyName, 1);
        };
    
        myClass.MyProperty = "testing";
        Assert.IsTrue(receivedEvents.ContainsKey("MyProperty"));
        Assert.AreEqual(1, receivedEvents["MyProperty"]);
        Assert.IsTrue(receivedEvents.ContainsKey("MyOtherProperty"));
        Assert.AreEqual(1, receivedEvents["MyOtherProperty"]);
    }
    
    0 讨论(0)
提交回复
热议问题