The key to Unit Testing graphical applications is to make sure that all most all of the business logic is in a separate class and not in the code behind.
Design patterns like Model View Presenter and Model View Controller can help when designing such a system.
To give an example:
public partial class Form1 : Form, IMyView
{
MyPresenter Presenter;
public Form1()
{
InitializeComponent();
Presenter = new MyPresenter(this);
}
public string SomeData
{
get
{
throw new NotImplementedException();
}
set
{
MyTextBox.Text = value;
}
}
private void button1_Click(object sender, EventArgs e)
{
Presenter.ChangeData();
}
}
public interface IMyView
{
string SomeData { get; set; }
}
public class MyPresenter
{
private IMyView View { get; set; }
public MyPresenter(IMyView view)
{
View = view;
View.SomeData = "test string";
}
public void ChangeData()
{
View.SomeData = "Some changed data";
}
}
As you can see, the Form only has some infrastructure code to thy everything together. All your logic is inside your Presenter class which only knows about a View Interface.
If you want to unit test this you can use a Mocking tool like Rhino Mocks to mock the View interface and pass that to your presenter.
[TestMethod]
public void TestChangeData()
{
IMyView view = MockRepository.DynamickMock<IMyView>();
view.Stub(v => v.SomeData).PropertyBehavior();
MyPresenter presenter = new MyPresenter(view);
presenter.ChangeData();
Assert.AreEqual("Some changed data", view.SomeData);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…