gpt4 book ai didi

c# - 使用最小起订量测试 WinForms MVP 和事件机制

转载 作者:行者123 更新时间:2023-11-30 17:16:01 24 4
gpt4 key购买 nike

我一直在我的应用程序中使用 MVP 模式。但是我在测试单击按钮后调用的方法时遇到问题。这是代码:

public interface IControl
{
bool Enabled { get; set; }
string Text { get; set; }
}

public interface IButton : IControl
{
event EventHandler Click;
}

public class Button : System.Windows.Forms.Button, IButton
{ }

public interface IForm : IControl
{
void Show();
void Close();
}

public interface IView : IForm
{
IButton Button1 { get; }
}

public partial class View : Form, IView
{
public View()
{
InitializeComponent();
}

#region IView Members

public IButton Button1
{
get { return button1; }
}

#endregion
}

public class Presenter
{
IView view;

public Presenter(IView view)
{
this.view = view;
this.view.Button1.Click += ButtonClick;
this.view.Show();
}

private void ButtonClick(object sender, EventArgs e)
{
view.Button1.Text= "some text";
}
}

问题是我不知道如何编写测试以便调用我的 ButtonClick 方法。我试过这样:

var view = new Mock<IView>();
view.Setup(x => x.Button1).Returns(new Mock<IButton>().SetupAllProperties().Object);
Presenter presenter = new Presenter(view.Object);
view.Raise(x => x.Button1.Click+= null, EventArgs.Empty);
Assert.AreEqual("some text", view.Object.Button1.Text);

我认为问题出在这一行:

this.view.Button1.Click += ButtonClick;

Click 事件似乎不记得 ButtonClick 方法。如何让Click to be stub正常工作。欢迎任何建议。提前致谢。问候,瓦依达

编辑:我在创建 SubscribeOnClick(EventHandler click) 时能够做到这一点;我的 IButton 界面中的方法,而不是事件 EventHandler Click。我在记得方法的地方制作了一些 ButtonMock。但是,如果有人知道更好的解决方案,请与我分享。

最佳答案

也许使用 command pattern 不是一个坏主意这里。你的IView是非常特定于实现的,因为它有规定数量的控件,这些控件应该有一个 Click事件(我知道这是一个例子,但仍然......)。

命令模式的一个简单实现是让 IView有一个List<Action>由演示者提供,并让 View 的特定实现决定如何触发这些操作,例如通过做

this.button1.Click += (sender, e) => this.Actions[0]();

模拟对象不需要有 Click 事件(Moq 甚至可能不支持,我不确定)。您可以让它触发其中一个 Action 。

关于c# - 使用最小起订量测试 WinForms MVP 和事件机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7570343/

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