C#使用MSTest進行單元測試的示例代碼
更新時間:2023年12月22日 09:28:31 作者:rjcql
MSTest是微軟官方提供的.NET平臺下的單元測試框架,這篇文章主要為大家詳細介紹了C#如何使用MSTest進行單元測試,感興趣的小伙伴可以參考一下
寫在前面
MSTest是微軟官方提供的.NET平臺下的單元測試框架;可使用DataRow屬性來指定數(shù)據,驅動測試用例所用到的值,連續(xù)對每個數(shù)據化進行運行測試,也可以使用DynamicData 屬性來指定數(shù)據,驅動測試用例所用數(shù)據的成員的名稱、種類(屬性、默認值或方法)和定義類型(默認情況下使用當前類型)
代碼實現(xiàn)
新建目標類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 });
}
}執(zhí)行結果
打開命令行窗口執(zhí)行以下命令:
dotnet test

符合預期結果
到此這篇關于C#使用MSTest進行單元測試的示例代碼的文章就介紹到這了,更多相關C# MSTest單元測試內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C# 使用 OleDbConnection 連接讀取Excel的方法
這篇文章主要介紹了C# 使用 OleDbConnection 連接讀取Excel的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-12-12

