C#使用MSTest進行單元測試的示例代碼
寫在前面
MSTest是微軟官方提供的.NET平臺下的單元測試框架;可使用DataRow屬性來指定數(shù)據(jù),驅(qū)動測試用例所用到的值,連續(xù)對每個數(shù)據(jù)化進行運行測試,也可以使用DynamicData 屬性來指定數(shù)據(jù),驅(qū)動測試用例所用數(shù)據(jù)的成員的名稱、種類(屬性、默認值或方法)和定義類型(默認情況下使用當前類型)
代碼實現(xiàn)
新建目標類DataChecker,增加待測試的方法,內(nèi)容如下:
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 }); } }
執(zhí)行結(jié)果
打開命令行窗口執(zhí)行以下命令:
dotnet test
符合預期結(jié)果
到此這篇關(guān)于C#使用MSTest進行單元測試的示例代碼的文章就介紹到這了,更多相關(guān)C# MSTest單元測試內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C# 使用 OleDbConnection 連接讀取Excel的方法
這篇文章主要介紹了C# 使用 OleDbConnection 連接讀取Excel的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12淺談C#各種數(shù)組直接的數(shù)據(jù)復制/轉(zhuǎn)換
下面小編就為大家?guī)硪黄獪\談C#各種數(shù)組直接的數(shù)據(jù)復制/轉(zhuǎn)換。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08