65.9K
CodeProject 正在变化。 阅读更多。
Home

创建 C# 代码的单元测试

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.52/5 (52投票s)

2012 年 6 月 7 日

CPOL

4分钟阅读

viewsIcon

527030

此测试用例旨在理解自动化单元测试的有用性

引言

当我们创建一个 C# 库(被其他应用程序使用的 API)时,我们不确定应用程序开发人员可能会如何使用它。他们可能会向我们的 API 函数传递不正确的参数信息。为了验证所有场景,我们需要创建代码来检查和验证我们的 API 方法。

有时我们需要修改我们的方法,但没有时间进行冒烟测试。在这种情况下,如果我们有自动化单元测试,我们可以轻松检查是否有任何地方出错。为了成功验证我们的方法/类,我们需要为我们的代码实现更高的代码覆盖率。

使用代码 

在这里,我们将看到如何使用单元测试框架来测试我们的代码。我创建了一个示例方法来解释测试框架。请查看下面的 API 方法。
  
public class ApplicationCodeClass
    {
        public string combineArrayStringWithSpace(string[] stringArray)
        {
            string str = default(string);

            foreach (string item in stringArray)
            {
                str += item + " ";
            }

            return str.Trim();
        }
    }  

现在让我们看看 API 消费者可能犯下的所有可能错误……!!!!

1) stringArray 可能为 null/空

2) stringArray 的某个元素包含空格

3) 积极场景,一切正常,我们需要检查预期的行为。

可能还有更多可能性,但让我们考虑以上三种情况,我们需要检查我们的 API 方法是否可以处理这些情况。我们需要检查我们的自动化单元测试通过了多少规则。

创建您的第一个单元测试(分步)

完成 API 开发后,您可以创建开发人员测试用例来验证您的代码。我使用的是 Visual Studio 2010 Ultimate 版本。所以不知道下面的选项是否对您可见。但您可以使用 Microsoft.VisualStudio.QualityTools.UnitTestFramework 命名空间来创建单元测试。

下一步是创建自动化单元测试用例。右键单击您的代码文件,会出现“创建单元测试...”选项。

选择上述选项后,系统会提示您选择要创建自动化测试用例的方法。Visual Studio 会以自己的方式创建一些可能的场景。下面是选择方法以创建单元测试的快照。稍后我们还将看到如何手动创建。

正如您在输出中看到的,“UnitTestProject”项目已可用(就我而言)。您在那里可能看不到这样的项目。当您单击“确定”按钮时,系统会提示您输入项目名称,然后创建项目。

自动化创建的测试方法看起来会是这样

  /// <summary>
        ///A test for combineArrayStringWithSpace
        ///</summary>
        [TestMethod()]
        public void combineArrayStringWithSpaceTest()
        {
            ApplicationCodeClass target = new ApplicationCodeClass(); // TODO: Initialize to an appropriate value
            string[] stringArray = null; // TODO: Initialize to an appropriate value
            string expected = string.Empty; // TODO: Initialize to an appropriate value
            string actual;
            actual = target.combineArrayStringWithSpace(stringArray);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }  

让我们创建自己的测试方法

        [TestMethod]
        public void PossitiveSchenarioForChecking_combineArrayStringWithSpace()
        {
            string expectedResult = "Today is the wonderful day of my life";
            string[] actualStringArray = new string[] { "Today", "is", "the", "wonderful", "day", "of", "my", "life" };
            ApplicationCodeClass appObject = new ApplicationCodeClass();

            string actualResult = appObject.combineArrayStringWithSpace(actualStringArray);
            Assert.AreEqual<string>(expectedResult, actualResult);
        }  

正如我们之前提到的,使用我们的 API 方法有 3 种可能的情况。Visual Studio 自动化测试用例涵盖了我们的第一种情况,而上面的测试用例将满足我们的第三种情况。同样,您可以通过在上述测试方法中的 actualStringArray 变量中传递空格来创建第二种情况。

测试用例的类型

我们可以为我们的 C# 库代码创建功能测试用例以及单元测试用例。

功能测试用例

1) 它将检查我们方法的 [功能](https://www.google.com/search?q=functionality) 和行为。

2) 如果我们向函数/方法传递了不正确的参数,它还将检查函数是否不会行为异常。

3) 我们涵盖了“它不应该做什么?”。这也被称为负功能测试用例。

4) 我们涵盖了“它应该做什么?”。这也被称为正功能测试用例。

单元测试用例

1) 我们在单元测试用例中涵盖了代码的每一个单元。作为测试人员,我们有责任检查我们的绝大部分代码是否都包含在单元测试用例中。

举个例子

if(Textbox1.Text == "ABC")
{
Response.Write("ABC is typed");
} 
else
{
Response.Write("ABC is not typed"); 
} 
  

在上面的代码中,如果我们只用“ABC”作为文本来检查 TextBox1 函数,那么我们的所有代码都不会被覆盖。我们还需要用不含“ABC”作为文本的值来测试。只有这样,我们才能说我们的代码 100% 被我们的测试用例覆盖。

访问私有变量以测试代码单元

我的类代码

    public class sampleClass
    {
        private int _classid;
        private string _name;
        public sampleClass()
        {}
        public sampleClass(int classId,string Name)
        {
            this._classid = classId;
            this._name = Name;
        }
    }  

我的访问私有变量的测试方法

 [TestClass]
    public class MyTestClass
    {
        [Microsoft.VisualStudio.TestTools.UnitTesting.TestMethod]
        public void MyTestMethod()
        {
            sampleClass newSampleClass = new sampleClass(2, "Amit Gajjar");
            Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject pobject = new Microsoft.VisualStudio.TestTools.UnitTesting.PrivateObject(newSampleClass);

            Assert.AreEqual<int?>(2, pobject.GetFieldOrProperty("_classid") as int?);
            Assert.AreEqual<string>("Amit Gajjar", pobject.GetFieldOrProperty("_name") as string);
        }
    }

从上面的测试用例中,您可以看到最后两个 Assert 方法。我们可以从我们的程序集类中访问 _classid_name 私有变量。通过这种方式,我们可以确保我们的类的私有变量按照我们的预期正确设置。如果这个简单的例子不能清楚您为何需要检查私有变量的想法,那么请考虑一个示例:当我们在一个转换器类中将温度单位从摄氏度转换为华氏度时。如果我们传入摄氏温度,它应该将其转换回华氏度。那时,如果我们的类发生更改或给出不正确的结果,则测试工程师可以捕获该错误。

最后的几句话

希望这篇文章能帮助您创建测试用例。欢迎您的所有建议并表示赞赏。



© . All rights reserved.