如何为此类中的方法编写单元测试?

时间:2014-12-14 20:32:54

标签: c# unit-testing

如何在此示例类中为derov这样的方法编写单元测试?我想有一个例子,说明如何在代码中编写一个测试用例,以测试只有大字母的字符串输入是否会给出我期望的结果。

编辑:我已经通过编写一个测试用例解决了这个问题,例如下面的课程上面发布的测试用例。

   ///If the expected result and the res variable is equal then the test case has not detected a   fault.
   [TestCase]
    public void TestStringWithOnlyBigConsonantsDerov()
    {
  //declare a string res = classname.methodname("string"); 
        string res = rovar.derov("BOBCOCFOFGOGHOHJOJKOKLOL")
  //check if equal ("expected result", variable holding real result)
        Assert.AreEqual("BCFGHJKL", res); 
    }

class CodeToTest
{
    static class danish
    {
        static string lower_consonants = "bcdghjklmnpqrstvwxz";
        static string upper_consonants = "BCFGHJKLMNPQRSTVWXZ";

        /// <summary>
        /// Encode the string to danish.
        /// Normal is a parameter that contains text which a user types in and 
        /// which shall be translated into danish. 
        /// </summary>
        /// <param name="normal">Normal string.</param>
        /// <returns>Encoded string.</returns>
        public static string danish(string normal)
        {
            if (normal == null) 
                return null;

            System.Text.StringBuilder builder = new System.Text.StringBuilder();
            foreach (char c in normal)

                if (lower_consonants.Contains(c.ToString()))
                    builder.Append(c + "o" + c);


                else if (upper_consonants.Contains(c.ToString())) 
                    builder.Append(c + "O" + c);

                else
                    builder.Append(c);

            return builder.ToString();
        }

        /// <summary>
        /// Decode a string from danish.
        /// </summary>
        /// <param name="dan">Encoded string.</param>
        /// <returns>Normal string.</returns>
        public static string derov(string dan)
        {
            if (dan == null)
                return null;

            foreach (char c in lower_consonants)
                dan = dan.Replace(c + "o" + c, c.ToString());

            foreach (char c in upper_consonants)
                dan = dan.Replace(c + "O" + c, c.ToString());

            return dan;
        }
    }
}

}

1 个答案:

答案 0 :(得分:1)

根据我的理解,班级没有内部状态;这两个字符串也可以是const,因为它们在初始化后永远不会被写入。函数danishderov都可以通过定义具有所需输出的参数列表并将其与参数进行比较来测试。此外,由于这是C#,因此Visual Studio具有集成的测试框架。也可以从命令行评估测试项目,这对自动化测试很有用。