[英]Moq Verify events triggered
class A
{
event EventHandler Event1;
}
var mock = new Mock<A>();
How do I verify Event1 was fired? 如何验证Event1被解雇? (without using manual event handlers / triggered flags)
(不使用手动事件处理程序/触发标志)
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();
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? 如果你有一个
Mock<A>
,那么你控制模拟,那么为什么要验证它已经做了你控制的事情?
That said, although I do use Moq's raise/raises, I still often use a flag with a lambda, which I find fairly clean: 也就是说,虽然我确实使用了Moq的加注/加注,但我仍然经常使用带有lambda的标志,我觉得相当干净:
bool eventWasDispatched = false; // yeah, it's the default
var a = new A();
a.Event1 += () => eventWasDispatched = true;
a.DoSomethingToFireEvent();
Assert.IsTrue(eventWasDispatched);
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.