.NET单元测试艺术(1) - 单元测试的基本知识

时间:2023-03-09 13:05:25
.NET单元测试艺术(1) - 单元测试的基本知识

List 1.1 一个要测试的SimpleParser类

using System;

namespace AOUT.CH1.Examples
{
    public class SimpleParser
    {
        public int ParseAndSum(string numbers)
        {
            )
            {
                ;
            }
            if(!numbers.Contains(","))
            {
                return int.Parse(numbers);
            }
            else
            {
                throw new InvalidOperationException("I can only handle 0 or 1 numbers for now!");
            }
        }
    }
}

List 1.2 一个用来测试SimpleParser类的简单方法

using System;
using System.Reflection;
using AOUT.CH1.Examples;

namespace AOUT.Ch1.Examples.Tests
{
    class SimpleParserTests
    {
        public static void TestReturnsZeroWhenEmptyString()
        {
            //use reflection to get the current method's name
            string testName = MethodBase.GetCurrentMethod().Name;
            try
            {
                SimpleParser p = new SimpleParser();
                int result = p.ParseAndSum(string.Empty);
                )
                {
                    TestUtil.ShowProblem(testName, "Parse and sum should have returned 0 on an empty string");
                }
            }
            catch (Exception e)
            {
                TestUtil.ShowProblem(testName, e.ToString());
            }
        }
    }
}

List 1.3 利用简单的控制台程序运行测试

using System;

namespace AOUT.Ch1.Examples.Tests
{
    public class MainClass
    {
        public static void Main(string[] args)
        {
            try
            {
                SimpleParserTests.TestReturnsZeroWhenEmptyString();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }
}

List 1.4 使用ShowProblem方法的一个更通用的实现

using System;

namespace AOUT.Ch1.Examples.Tests
{
    public class TestUtil
    {
        public static void ShowProblem(string test,string message )
        {
            string msg = string.Format(@"
---{0}---
       {1}
--------------------
", test, message);
            Console.WriteLine(msg);
        }
    }
}