class A
{
event EventHandler Event1;
}
var mock = new Mock<A>();
如何验证Event1被解雇? (不使用手动事件处理程序/触发标志)
答案 0 :(得分:22)
var mock = new Mock<IInterfaceWithEvent>;
mock.Raise(e => e.MyEvent += null, EventArgs.Empty);
mock.VerifyAll();
或者如果您想确保该行为引发事件,您的设置应如下所示:
mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, EventArgs.Empty);
// ...
mock.VerifyAll();
答案 1 :(得分:21)
我不确定我真的明白你为什么这么问。如果您有一个Mock<A>
,那么您可以控制模拟,以便验证它是否已经完成了您控制的操作?
那就是说,虽然我确实使用了Moq的加注/加注,但我仍然经常使用带有lambda的标志,我觉得相当干净:
bool eventWasDispatched = false; // yeah, it's the default
var a = new A();
a.Event1 += () => eventWasDispatched = true;
a.DoSomethingToFireEvent();
Assert.IsTrue(eventWasDispatched);
答案 2 :(得分:0)
这样的事情怎么样?
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;
}
在您的测试中:
// 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();
}