【发布时间】:2015-09-15 07:23:15
【问题描述】:
public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, Color foreColor, TextFormatFlags flags);
我有一个用于我的 ExtendedComboBox 的测试器应用程序。 下面在代码中给出的所有字符串项目都在我的测试应用程序的 ComboBox 项目中。如何对上述方法进行单元测试,因为它返回 void? 测试 TextRenderer.Drawtext 的另一种方法是什么?是否有任何替代方法来测试绘制 ComboBox 文本的 OnDrawItem 方法。
[TestMethod()]
public void ExtendedComboBoxOnDrawPrefixTest()
{
ExtendedComboBox cboTest = new ExtendedComboBox ();
// List of strings having special characters.
string[] items = {
"&One",
"T&wo",
"E!xclamation",
"Am@persat",
"H#ash",
"Dollar$Sign",
"Perc%ent",
"Ci^rcumflex",
"Ast*erisk",
"Hy-phen",
"Und_erscore",
"pl+us",
"Equ=als",
"Col:on",
"Semi;colon",
"Co'mma",
"Inverted\"Comma",
"Apos'trophe",
"Pip|e",
"Open{Brace",
"Close}Brace",
"OpenBr[acket",
"CloseBr]acket",
"BackS\\lash",
"ForwardSl/ash",
"LessT<han",
"Greate>rThan",
"Questio?nMark",
"Do.t",
"Three",
"Four",
"Five",
"Six",
"This is a really extremely long string value for a combobox to display."
};
cboTest.Items.AddRange(items);
// To test that all the items have the same kind of prefixes
for (int index = 0; index < cboTest.Items.Count; index++)
{
String expectedText = GetExtendedComboBoxText(cboTest, items[index]);
Assert.AreEqual(items[index], , String.Format("Item '{0}' returned an string", cboTest.Items[index]));
}
}
/// <summary>
/// Compare the ComboBoxText of the passed string with respect to the DC, Font, ForeColor and TextFormatFlags.
/// Draw the item
/// </summary>
private string GetExtendedComboBoxText(Control cboTest, string itemToTest)
{
TextFormatFlags textFormatflags = TextFormatFlags.NoPrefix;
Color foreColor = SystemColors.HighlightText;
return (TextRenderer.DrawText(cboTest.CreateGraphics(), itemToTest, cboTest.Font, new Point(cboTest.Bounds.X, cboTest.Bounds.Y), foreColor, textFormatflags)).Text;
}
【问题讨论】:
-
通常您不会对返回 void 或不会改变某些对象状态的方法进行单元测试。我能想到的单元测试的唯一方法是将输出渲染到某个图像文件并手动验证它们看起来是否正确,但是如果方法调用成功(不是@ 987654323@),这是你唯一可以测试的东西。
-
@RonBeyer 实际上在这种情况下,OP 不应该测试该方法,因为 Microsoft 已经为我们做了它。(这是一种 BCL 方法)在我的回答中,我会详细解释它。
标签: c# unit-testing