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
.
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;
}