Substitutes for INotifyPropertyChanged

403 views
Skip to first unread message

Garth Kidd

unread,
Oct 27, 2010, 11:44:48 PM10/27/10
to NSubstitute
I can't use the Raise.Event() or Raise.Event<TEventArgs>() syntax with
a Substitute.For<INotifyPropertyChanged> because
EventHandlerWrapper<PropertyChangedEventArgs> cannot be cast to
PropertyChangedEventHandler.

This doesn't compile:

[Test]
public void CanSubstituteForINotifyPropertyChanged() {
bool fired = false;
var dummy = Substitute.For<INotifyPropertyChanged>();
dummy.PropertyChanged += (s, a) => { fired = true; };
var args = new PropertyChangedEventArgs("Dummy");
dummy.PropertyChanged +=
Raise.Event<PropertyChangedEventArgs>(dummy, args);
Assert.True(fired);
}

Some poking around in the source makes it appear that I should be able
to call Raise.Event manually and then add null to
dummy.PropertyChanged, but that doesn't work:

[Test]
public void CanSubstituteForINotifyPropertyChanged() {
bool fired = false;
var dummy = Substitute.For<INotifyPropertyChanged>();
dummy.PropertyChanged += (s, a) => { fired = true; };
var args = new PropertyChangedEventArgs("Dummy");
var raising = Raise.Event<PropertyChangedEventArgs>(dummy,
args);
dummy.PropertyChanged += null;
Assert.True(fired);
}

Any ideas?

Yours,
Garth.

David Tchepak

unread,
Oct 28, 2010, 8:10:17 AM10/28/10
to nsubs...@googlegroups.com
Hi Garth,

The issue is that PropertyChanged is declared as "event PropertyChangedEventHandler", where PropertyChangedEventHandler is a delegate rather than something which inherits from EventHander.

We're working on trying to find a good syntax to raise events declared like this, and it will hopefully be in the repo in the next day or two. Until then you can force NSubstitute to use the correct Raise.Event overload like this:

        [Test]
        public void CanRaiseNotifyPropertyChangedEvent()
        {
            var sub = Substitute.For<INotifyPropertyChanged>();
            var wasRaised = false;
            sub.PropertyChanged += (sender, args) => wasRaised = true;
            sub.PropertyChanged += Raise.Event<PropertyChangedEventHandler>(this, new PropertyChangedEventArgs("test"));
            Assert.That(wasRaised);
        }

( If you're interested in the source, this is the overload that currently lives here: http://bit.ly/c618MJ )

Appreciate you sending this through; it's a much more obvious example than the previous one we'd found. :)

Regards,
David


--
You received this message because you are subscribed to the Google Groups "NSubstitute" group.
To post to this group, send email to nsubs...@googlegroups.com.
To unsubscribe from this group, send email to nsubstitute...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/nsubstitute?hl=en.


Reply all
Reply to author
Forward
0 new messages