How to raise NotifyCollectionChangedEventArgs with XUnit

250 Views Asked by At

I have a class implementing INotifyCollectionChanged and I would like to test if the CollectionChanged event is raised for specific scenarios.

I've tried the code bellow but I am getting compiler errors and so far I couldn't find a solution.

[Fact]  
public void RaiseOnAddition()
{
  Action addition = () => Collection["new key"] = 3;

  Assert.Raises<NotifyCollectionChangedEventArgs>(
    handler => Collection.CollectionChanged += handler, // compiler error
    handler => Collection.CollectionChanged -= handler, // compiler error
    addition);
}

Cannot implicitly convert type 'System.EventHandler<System.Collections.Specialized.NotifyCollectionChangedEventArgs>' to 'System.Collections.Specialized.NotifyCollectionChangedEventHandler'

The problem lies in the fact that handler is EventHandler<NotifyCollectionChangedEventArgs> where I want a NotifyCollectionChangedEventHandler<NotifyCollectionChangedEventArgs>.

Note: There's a specific function to test PropertyChanged (Assert.PropertyChanged) but not for CollectionChanged.

2

There are 2 best solutions below

0
Themelis On BEST ANSWER

I guess there's no alternative than doing something like this,

[Fact]  
public void RaiseOnAddition()
{
  var timesRaised = 0;

  NotifyCollectionChangedEventHandler handler += () => ++timesRaised;

  Collection["new key"] = 3;

  Assert.Equals(1, timesRaised);

  NotifyCollectionChangedEventHandler handler -= () => ++timesRaised;
}
0
Yevheniy Tymchishin On
public class TestClass : INotifyCollectionChanged
{
  public event NotifyCollectionChangedEventHandler? CollectionChanged;

  public void RaiseCollectionChanged()
  {
    CollectionChanged?.Invoke(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
  }
}
public class TestClassTests
{
  [Fact]
  public void RaiseOnAddition()
  {
    var counter = 0;
    var testee = new TestClass();
    testee.CollectionChanged += (s, e) => counter++;
    testee.RaiseCollectionChanged();
    testee.RaiseCollectionChanged();
    Assert.Equal(2, counter);
  }
}