Moq Verify事件已触发

本文关键字:事件 Verify Moq | 更新日期: 2023-09-27 17:59:16

class A
{
    event EventHandler Event1;
}
var mock = new Mock<A>();

如何验证Event1是否已启动?(不使用手动事件处理程序/触发标志(

Moq Verify事件已触发

我不确定我是否真的理解你为什么这么问。如果你有一个Mock<A>,那么你就控制了mock,那么为什么要验证它做了你控制的事情呢?

也就是说,尽管我确实使用了Moq的提升/提升,但我仍然经常使用带有lambda的标志,我觉得它相当干净:

bool eventWasDispatched = false; // yeah, it's the default
var a = new A();
a.Event1 += () => eventWasDispatched = true;
a.DoSomethingToFireEvent();
Assert.IsTrue(eventWasDispatched);
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();

这样的东西怎么样?

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();
}