Reputation: 7301
class A
{
event EventHandler Event1;
}
var mock = new Mock<A>();
How do I verify Event1 was fired? (without using manual event handlers / triggered flags)
Upvotes: 20
Views: 19867
Reputation: 25742
var mock = new Mock<IInterfaceWithEvent>();
mock.Raise(e => e.MyEvent += null, EventArgs.Empty);
mock.VerifyAll();
or if you want to make sure that act raises an event, your setup should look like:
mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, EventArgs.Empty);
// ...
mock.VerifyAll();
Upvotes: 27
Reputation: 4482
How about something like this?
public class MyClass : INotifyPropertyChanged
{
private string _name;
public string Name
{
get => _name;
set
{
_name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
In your tests:
// This interface contains signatures which match your event delegates
public interface IPropertyChangedEventHandler
{
void PropertyChangedHandler(object sender, PropertyChangedEventArgs e);
}
public void WhenSettingNameNotifyPropertyChangedShouldBeTriggered()
{
// Arrange
var sut = new Mock<MyClass>();
var handler = new Mock<IPropertyChangedEventHandler>();
handler.Setup(o => o.PropertyChangedHandler(sut, new PropertyChangedEventArgs(nameof(MyClass.Name))));
sut.PropertyChanged += handlerMock.Object.PropertyChangedHandler;
// Act
sut.Name = "Guy Smiley";
// Assert
handler.Verify();
}
Upvotes: 0
Reputation: 46479
I'm not sure I really understand why you ask. If you have a Mock<A>
, then you control the mock so why verify that it has done something that you control?
That said, although I do use Moq's raise/raises, I still often use a flag with a lambda, which I find fairly clean:
bool eventWasDispatched = false; // yeah, it's the default
var a = new A();
a.Event1 += () => eventWasDispatched = true;
a.DoSomethingToFireEvent();
Assert.IsTrue(eventWasDispatched);
Upvotes: 33