单元测试之NUnit二

NUnit 分三篇文章介绍,入门者可阅读文章,有基础者直接参考官方文档。初次写博客,望大家指点。

导航:
单元测试之NUnit一
单元测试之NUnit二
单元测试之NUnit三

本文介绍常用的NUnit属性特性和断言。

常用属性

更多属性参考官方文档

1. Test Attribute

标记一个方法为测试方法。

        /// <summary>
        /// 简单标记方法为测试方法
        /// </summary>
        [Test]
        public void Add()
        {
            Assert.AreEqual(4, 2 + 2);
        }
        
         /// <summary>
        /// 添加说明内容,等同于DescriptionAttribute属性
        /// </summary>
        //[Test(Description = "这是说明内容")]
        [Test,Description("这是说明属性")]
        public void Add()
        {
            Assert.AreEqual(4, 2 + 2);
        }
        
        // 标记异步方法
        [Test]
        public async Task AddAsync()
        {
            /* ... */
        }
        
        // 如果测试方法有返回值,要使用ExpectedResult校验
        [Test(ExpectedResult = 4)]
        public int TestAdd()
        {
            return 2 + 2;
        }
        
        // 异步含返回值的测试方法
        [Test(ExpectedResult = 4)]
        public async Task<int> TestAddAsync()
        {
            //await do something;
            return 2 + 2;
        }
2. TestFixture Attribute

标记一个类为测试类。从2.5版本开始,对于非参数化、非泛型化测试类是可选的。只要类包含Test、TestCase、TestCaseSource属性标记的方法,都会被视为一个测试类。

TestFixture大多数用来构造参数,被标记的类必须有个对应的构造函数。

简单例子:

/// <summary>
    /// 使用TestFixture标记会生成三个测试,是每个测试方法执行三次
    /// </summary>
    [TestFixture("hello", "hello", "goodbye")]
    [TestFixture("zip", "zip")]
    [TestFixture(42, 42, 99)]
    public class TestFixtureAttributeTest
    {
        private string eq1;
        private string eq2;
        private string neq;

        public TestFixtureAttributeTest(string eq1, string eq2, string neq)
        {
            this.eq1 = eq1;
            this.eq2 = eq2;
            this.neq = neq;
        }

        public TestFixtureAttributeTest(string eq1, string eq2)
            : this(eq1, eq2, null) { }

        public TestFixtureAttributeTest(int eq1, int eq2, int neq)
        {
            this.eq1 = eq1.ToString();
            this.eq2 = eq2.ToString();
            this.neq = neq.ToString();
        }

        [Test]
        public void TestEquality()
        {
            Assert.AreEqual(eq1, eq2);
            if (eq1 != null && eq2 != null)
                Assert.AreEqual(eq1.GetHashCode(), eq2.GetHashCode());
        }

        [Test]
        public void TestInequality()
        {
            Assert.AreNotEqual(eq1, neq);
            if (eq1 != null && neq != null)
                Assert.AreNotEqual(eq1.GetHashCode(), neq.GetHashCode());
        }

还可以标记类型:

    /// <summary>
    /// 标记TList会以两种类型来执行。
    /// </summary>
    /// <typeparam name="TList"></typeparam>
    [TestFixture(typeof(ArrayList))]
    [TestFixture(typeof(List<int>))]
    public class IList_Tests<TList> where TList : IList, new()
    {
        private IList list;

        [SetUp]
        public void CreateList()
        {
            this.list = new TList();
        }

        [Test]
        public void CanAddToList()
        {
            list.Add(1); list.Add(2); list.Add(3);
            Assert.AreEqual(3, list.Count);
        }
    }
3. SetUp And TearDown Attribute

标记一个方法在测试前或者测试后执行,以便初始化或者清理一些参数。

 public class SetUpAndTearDownTest
    {
        [SetUp]
        public void SetUp()
        {
            Console.WriteLine("我在测试前执行");
        }
        [Test]
        public void Test()
        {
            Console.WriteLine("我在测试时执行");
            Assert.Pass();
        }

        [TearDown]
        public void TearDown()
        {
            Console.WriteLine("我在测试后执行");
        }
    }

执行Test测试方法,依次输出:
我在测试前执行
我在测试时执行
我在测试后执行

4. TestCase Attribute

TestCase有两个作用:
标记为测试方法;
为方法提供测试参数。

public class TestCaseTest
    {
        [TestCase(12, 3, 4)]
        [TestCase(12, 2, 6)]
        [TestCase(12, 4, 3)]
        public void DivideTest(int n, int d, int q)
        {
            Assert.AreEqual(q, n / d);
        }

        /// <summary>
        /// TestCase 可以包含条件属性:Author、Category、Description、ExcludePlatform、ExpectedResult、Explicit、Ignore、IgnoreReason、IncludePlatform、Reason、TestName、TestOf 
        /// </summary>
        /// <param name="n"></param>
        /// <param name="d"></param>
        /// <returns></returns>
        [TestCase(12, 3, ExpectedResult = 4)]
        [TestCase(12, 2, ExpectedResult = 6)]
        [TestCase(12, 4, ExpectedResult = 3)]
        public int DivideTest(int n, int d)
        {
            return n / d;
        }
    }

常用断言

更多参考官方文档 的Pages页。

1. Assert.AreEqual
        [Test]
        public void AreEqual_Test()
        {
            Assert.AreEqual(5, 5.0);//Successed.double 和 int 会内部转化比较。
            //Assert.AreEqual(5.0, "5.0");//Failed.double和string类型不能相互比较。
            List<Dictionary<int, string>> dic1 = new List<Dictionary<int, string>>
            {
                new Dictionary<int, string>(){ { 1,"one"},{2,"two" } }
            };
            List<Dictionary<int, string>> dic2 = new List<Dictionary<int, string>>
            {
                new Dictionary<int, string>(){{1,"one"}, { 2, "two" } }
            };
            Assert.AreEqual(dic1, dic2);//Successed.泛型也可以比价,会比较内部的值,且只能一一对应。
            List<int> list = new List<int> { 1, 3, 2 };
            List<double> list2 = new List<double> { 1.0, 2.0, 3.0 };
            Assert.AreEqual(list, list2);//Failed.
        }
2. Assert.AreSame
        [Test]
        public void AreSame_Test()
        {
            BankAccount A = new BankAccount(1000);
            BankAccount B = A;
            Assert.AreSame(A, B);// Successed 引用类型对象
            double a = 5;
            double b = 5;
            Assert.AreSame(a, b);//Failed 值类型两个值相同对象不相同。
        }
2. Assert.True

判断条件是否为真。

 bool result = true;
 Assert.IsTrue(result);

组合条件判断 Assert.That + Constraint

以前老版本有 Assert.IsNullOrEmpty("");这样的断言,新版本之后就没有了。那如果要满足这种判断怎么处理呢?
NUnit提供了一系列条件组合,配合 Assert.That 的使用可以灵活多变。
Constraint的使用参考文档

1. 取代 Assert.IsNullOrEmpty
Assert.That("1", Is.Null.Or.Empty);

本文就举一两例子介绍NUnit的使用,关于Attribute、Assert和Condition的使用得多参考官方文档学习(文中已经贴了链接)。

原文地址:https://www.cnblogs.com/jimizhou/p/11412301.html