visual studio单元测试

测试代码:

 class Cmp
    {
        public int Largest(int[] list)
        {
            if (list.Length == 0)
                throw new ArgumentException("Empty list");
            int index, max = Int32.MinValue;
            for (index = 0; index < list.Length; index++)
            {
                if (list[index] > max)
                    max = list[index];
            }
            return max;
        }
    }

测试步骤:

1.新建测试项目

2. 新建Cmp类,将测试代码放进去

 3.在测试类中编写测试用例

代码:

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject2
{
    [TestClass]
    public class UnitTest1
    {
        Cmp cmp = new Cmp();
        [TestMethod]
        public void TestMethod1()
        {
            int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int t1 = cmp.Largest(test1);
            Assert.AreEqual<Int32>(t1, 9);
        }
        [TestMethod]
        public void TestMethod2()
        {
            int[] test2 = { 2, 2, 2, 2, 2, 2, 2, 2, 2 };
            int t2 = cmp.Largest(test2);
            Assert.AreEqual<Int32>(t2, 2);
        }
        [TestMethod]
        public void TestMethod3()
        {
            int[] test3 = { -1, -8, -9, -6, 5, 7, 3, 4, -6 };
            int t3 = cmp.Largest(test3);
            Assert.AreEqual<Int32>(t3, 7);
        }
        [TestMethod]
        public void TestMethod4()
        {
            int[] test4 = { 0, 0, 0 };
            int t4 = cmp.Largest(test4);
            Assert.AreEqual<Int32>(t4, 0);
        }
        [TestMethod]
        public void TestMethod5()
        {
            int[] test5 = { };
            int t5 = cmp.Largest(test5);
            Assert.Fail();
        }
    }
}

 4.运行测试(右击运行测试)

 4.查看代码覆盖率

TestMethod1:

 

TestMethod2:

TestMethod3:

 

TestMethod4:

 

TestMethod5:

 

posted @ 2022-04-13 09:34  睡觉不困  阅读(252)  评论(0编辑  收藏  举报