51Testing
怬
µçÄÔ°æ

C# ʹÓÃMSTest½øÐе¥Ôª²âÊÔ

2024-3-04 09:30×÷ÕߣºrjcqlÀ´Ô´£ºCSDN

¡¡¡¡Ð´ÔÚÇ°Ãæ
¡¡¡¡MSTestÊÇ΢Èí¹Ù·½ÌṩµÄ.NETƽ̨ϵĵ¥Ôª²âÊÔ¿ò¼Ü£»¿ÉʹÓÃDataRowÊôÐÔÀ´Ö¸¶¨Êý¾Ý£¬Çý¶¯²âÊÔÓÃÀýËùÓõ½µÄÖµ£¬Á¬Ðø¶Ôÿ¸öÊý¾Ý»¯½øÐÐÔËÐвâÊÔ£¬Ò²¿ÉÒÔʹÓÃDynamicData ÊôÐÔÀ´Ö¸¶¨Êý¾Ý£¬Çý¶¯²âÊÔÓÃÀýËùÓÃÊý¾ÝµÄ³ÉÔ±µÄÃû³Æ¡¢ÖÖÀࣨÊôÐÔ¡¢Ä¬ÈÏÖµ»ò·½·¨£©ºÍ¶¨ÒåÀàÐÍ£¨Ä¬ÈÏÇé¿öÏÂʹÓõ±Ç°ÀàÐÍ£©¡£
¡¡¡¡´úÂëʵÏÖ
¡¡¡¡Ð½¨Ä¿±êÀàDataChecker£¬Ôö¼Ó´ý²âÊԵķ½·¨£¬ÄÚÈÝÈçÏ£º
¡¡¡¡    public class DataChecker
¡¡¡¡    {
¡¡¡¡        public bool IsPrime(int candidate)
¡¡¡¡        {
¡¡¡¡            if (candidate == 1)
¡¡¡¡            {
¡¡¡¡                return true;
¡¡¡¡            }
¡¡¡¡            return false;
¡¡¡¡        }
¡¡¡¡        public int AddInt(int first, int second)
¡¡¡¡        {
¡¡¡¡            int sum = first;
¡¡¡¡            for (int i = 0; i < second; i++)
¡¡¡¡            {
¡¡¡¡                sum += 1;
¡¡¡¡            }
¡¡¡¡            return sum;
¡¡¡¡        }
¡¡¡¡    }
¡¡¡¡ н¨µ¥Ôª²âÊÔÀàUnitTest1
¡¡¡¡namespace MSTestTester.Tests;
¡¡¡¡[TestClass]
¡¡¡¡public class UnitTest1
¡¡¡¡{
¡¡¡¡    private readonly DataChecker _dataChecker;
¡¡¡¡    public UnitTest1()
¡¡¡¡    {
¡¡¡¡        _dataChecker = new DataChecker();
¡¡¡¡    }
¡¡¡¡    [TestMethod]
¡¡¡¡    [DataRow(-1)]
¡¡¡¡    [DataRow(0)]
¡¡¡¡    [DataRow(1)]
¡¡¡¡    public void IsPrime_ValuesLessThan2_ReturnFalse(int value)
¡¡¡¡    {
¡¡¡¡        var result = _dataChecker.IsPrime(value);
¡¡¡¡ 
¡¡¡¡        Assert.IsFalse(result, $"{value} should not be prime");
¡¡¡¡    }
¡¡¡¡    [DataTestMethod]
¡¡¡¡    [DataRow(1, 1, 2)]
¡¡¡¡    [DataRow(2, 2, 4)]
¡¡¡¡    [DataRow(3, 3, 6)]
¡¡¡¡    [DataRow(0, 0, 1)] // The test run with this row fails
¡¡¡¡    public void AddInt_DataRowTest(int x, int y, int expected)
¡¡¡¡    {
¡¡¡¡        int actual = _dataChecker.AddInt(x, y);
¡¡¡¡        Assert.AreEqual(expected, actual,"x:<{0}> y:<{1}>",new object[] { x, y });
¡¡¡¡    }
¡¡¡¡    public static IEnumerable<object[]> AdditionData
¡¡¡¡    {
¡¡¡¡        get
¡¡¡¡        {
¡¡¡¡            return new[]
¡¡¡¡            {
¡¡¡¡            new object[] { 1, 1, 2 },
¡¡¡¡            new object[] { 2, 2, 4 },
¡¡¡¡            new object[] { 3, 3, 6 },
¡¡¡¡            new object[] { 0, 0, 1 },
¡¡¡¡        };
¡¡¡¡        }
¡¡¡¡    }
¡¡¡¡    [TestMethod]
¡¡¡¡    [DynamicData(nameof(AdditionData))]
¡¡¡¡    public void AddIntegers_FromDynamicDataTest(int x, int y, int expected)
¡¡¡¡    {
¡¡¡¡        int actual = _dataChecker.AddInt(x, y);
¡¡¡¡        Assert.AreEqual(expected, actual, "x:<{0}> y:<{1}>", new object[] { x, y });
¡¡¡¡    }
¡¡¡¡}
¡¡¡¡Ö´Ðнá¹û
¡¡¡¡´ò¿ªÃüÁîÐд°¿ÚÖ´ÐÐÒÔÏÂÃüÁ
¡¡¡¡dotnet test
¡¡¡¡ ·ûºÏÔ¤ÆÚ½á¹û¡£
¡¡¡¡±¾ÎÄÄÚÈݲ»ÓÃÓÚÉÌҵĿµÄ£¬ÈçÉ漰֪ʶ²úȨÎÊÌ⣬ÇëȨÀûÈËÁªÏµ51TestingС±à(021-64471599-8017)£¬ÎÒÃǽ«Á¢¼´´¦Àí
Èí¼þ²âÊÔ µ¥Ôª²âÊÔ
µ±Ç°Ã»ÓÐÆÀÂÛµã»÷·¢±íÆÀÂÛ

Ïà¹ØÔĶÁ