gpt4 book ai didi

c# - Moq - mock.Raise 应该在没有设置的情况下在测试单元中引发事件

转载 作者:IT王子 更新时间:2023-10-29 04:09:10 25 4
gpt4 key购买 nike

我有一个演示器类,它附加了一个注入(inject) View 的事件。现在我想测试演示者对事件的正确 react 。

这是 View 界面IView:

public interface IView 
{
event EventHandler MyEvent;
void UpdateView(string test);
}

这是实现 IView 的 View :

public partial class MyView : IView
{
public event EventHandler MyEvent;

public MyView()
{
this.combo.SelectedIndexChanged += this.OnSelectedIndexChanged;
}

public void UpdateView(string test)
{
this.textBox.Text = test;
}

private OnSelectedIndexChanged(Object sender, EventArgs e)
{
if (this.MyEvent != null)
{
this.MyEvent(sender, e);
}
}
}

这是被测演示者:

public class MyPresenter
{
private IView _view;
public MyPresenter(IView view)
{
this._view = view;
this._view.MyEvent += this.OnMyEvent;
}

private void OnMyEvent(Object sender, EventArgs e)
{
this._view.UpdateView();
}
}

这是测试夹具测试MyPresenter:

[TestClass]
public class MyPresenterFixture()
{
private MyPresenter testee;
private Mock<IView> mockView;

[TestMethod]
public void ShouldReactOnMyEvent()
{
// arrange
this.mockView = new Mock<IView>(MockBehavior.Strict);
this.testee = new MyPresenter(this.mockView.Object);

// act
this.mockView.Raise(mock => mock.MyEvent += null); // this does not fire

// assert and verify
this.mockView.Verify(mock => mock.UpdateView(It.IsAny<string>());
}
}

我正在使用 Moq 4。是否可以做我想做的事?

最佳答案

不需要传参吗?你的事件签名是EventHandler,也就是
(object sender, EventArgs e).

this.mockView.Raise(mock => mock.MyEvent += null, new EventArgs());

我从未使用过您在此处指定的重载...不过它似乎不正确。

关于c# - Moq - mock.Raise 应该在没有设置的情况下在测试单元中引发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6016854/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com