如何在C#中unit testingTextrenderer.DrawText方法

public static void DrawText(IDeviceContext dc, string text, Font font, Point pt, Color foreColor, TextFormatFlags flags); 

我有一个测试器应用程序,用于我的ExtendedComboBox。 以下代码中给出的所有String项都存在于我的测试器应用程序中的ComboBox项中。 如何对上面的方法进行unit testing,因为它返回void? 测试TextRenderer.Drawtext的另一种方法是什么? 是否有任何替代测试OnDrawItem方法来绘制ComboBox文本。

 [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", "LessTrThan", "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])); } } ///  /// Compare the ComboBoxText of the passed string with respect to the DC, Font, ForeColor and TextFormatFlags. /// Draw the item ///  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; } 

这是一个BCL方法,你不应该validationBCL方法的行为。

在UT中有一个假设; BCL的方法和类正常工作。 如果您validationBCL的方法,那么您将必须validationintbyteToString()等的行为…(因为您无法信任您的基础架构)

最重要的是你不应该validationBCL类的行为( Microsoft已经为你做了……)。 实际上,您应该假设该方法正常工作(而不是validation它),然后validation您正在使用具有正确参数的方法。

为了帮助我的开发人员,我创建了一个流程图,演示了当他们遇到这样一个问题时如何采取行动:(在我们的研发中,我们发现它非常实用。我们喜欢它影响我们研发的方式……)

在此处输入图像描述

在您的情况下,似乎预期的行为是可见的,因此您可以通过UIvalidation它作为您的Acceptance / Integration / Component测试的一部分……

如果您仍然希望将其validation为UT并且您的测试框架不允许您validation( Rhino MocksMoq等…)此方法,则应该使用其他工具(如MsFakes , Typemock )来包装方法或测试方法隔离器等……

以下代码段演示了使用MsFakes为方法设置期望的方法:

  [TestMethod] public void PutExpectationOnDrawText() { var wasExcute = false; System.Windows.Forms.Fakes.ShimTextRenderer .DrawTextIDeviceContextStringFontRectangleColorTextFormatFlags = (context, txt, font, pt, forecolor, flags) => { //the asserts on the orguments... //for example: Assert.IsNotNull(context); Assert.AreNotEqual(String.Empty, txt); //... wasExcute = true; }; //execute the method which is use DrawText Assert.IsTrue(wasExcute);//verify that the method was execute.... }