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#中使用servicestackredis操作redis的實例代碼
本篇文章主要介紹了在c#中使用servicestackredis操作redis的實例代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-06-06
C# Double轉(zhuǎn)化為String時的保留位數(shù)及格式方式
這篇文章主要介紹了C# Double轉(zhuǎn)化為String時的保留位數(shù)及格式方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02
vista和win7在windows服務中交互桌面權(quán)限問題解決方法:穿透Session 0 隔離
服務(Service)對于大家來說一定不會陌生,它是Windows 操作系統(tǒng)重要的組成部分。我們可以把服務想像成一種特殊的應用程序,它隨系統(tǒng)的“開啟~關(guān)閉”而“開始~停止”其工作內(nèi)容,在這期間無需任何用戶參與2016-04-04

