我正在为我的用户控件编写测试用例,该控件将使用MessageBox.Show进行提示,要求用户执行或取消操作。 我如何设计单元测试来模拟用户交互以进行进一步操作?
我不想重构将逻辑移动到中间层。 这只是获取用户同意并继续进行中间层调用的简单情况。 对于此场景重新构建UI的任何帮助/想法也将很有帮助。
click
事件。因此,您可能希望围绕此构建测试。private int MyFunction()
{
bool insideVariable = false;
if(insideVariable)
return 1;
else
return 2;
}
你永远无法对设置insideVariable为true的情况进行单元测试;你可以选择以下两种方法:
return 1
语句出现在你的中间层中的某个位置。return 1
语句成为GUI中的一个方法。然后你就可以测试该函数。应用程序前端应该很容易替换,因此不应存储任何业务逻辑。单元测试只是与你的主GUI并存的另一个前端。
new Form1().Button1_Click(this, null)
这样做。 - Jan JongboomMessageBox
的实际方法,如下所示:public class ClassUnderTest
{
private static Func<string, string, MessageBoxButtons, DialogResult>
_messageBoxLocator = MessageBox.Show;
public static Func<string, string, MessageBoxButtons, DialogResult>
MessageBoxDependency
{
get { return _messageBoxLocator; }
set { _messageBoxLocator = value; }
}
private void MyMethodOld(object sender, EventArgs e)
{
if (MessageBox.Show("test", "", MessageBoxButtons.YesNo) ==
System.Windows.Forms.DialogResult.Yes)
{
//Yes code
AnsweredYes = true;
}
else
{
//No code
}
}
public bool AnsweredYes = false;
public void MyMethod(object sender, EventArgs e)
{
if (MessageBoxDependency(
"testText", "testCaption", MessageBoxButtons.YesNo)
==
System.Windows.Forms.DialogResult.Yes)
{
//proceed code
AnsweredYes = true;
}
else
{
//abort code
}
}
}
然后测试方法(记得在顶部包含using Microsoft.VisualStudio.TestTools.UnitTesting;
)应该像这样:
[TestMethod]
public void ClassUnderTest_DefaultAnsweredYes_IsFalse()
{
var classUnderTest = new ClassUnderTest();
Assert.AreEqual(false, classUnderTest.AnsweredYes);
}
[TestMethod]
public void MyMethod_UserAnswersYes_AnsweredYesIsTrue()
{
//Test Setup
Func<string, string, MessageBoxButtons, DialogResult>
fakeMessageBoxfunction =
(text, caption, buttons) =>
DialogResult.Yes;
//Create an instance of the class you are testing
var classUnderTest = new Testing.ClassUnderTest();
var oldDependency = Testing.ClassUnderTest.MessageBoxDependency;
Testing.ClassUnderTest.MessageBoxDependency = fakeMessageBoxfunction;
try
{
classUnderTest.MyMethod(null, null);
Assert.AreEqual(true, classUnderTest.AnsweredYes);
//Assert What are you trying to test?
}
finally
{ //Ensure that future tests are in the default state
Testing.ClassUnderTest.MessageBoxDependency = oldDependency;
}
}
也许我们可以尝试微软官方的UI自动化?https://msdn.microsoft.com/zh-cn/library/aa348551.aspx