C# 使用MSTest进行单元测试

目录

写在前面

代码实现

执行结果


写在前面

MSTest是微软官方提供的.NET平台下的单元测试框架;可使用DataRow属性来指定数据,驱动测试用例所用到的值,连续对每个数据化进行运行测试,也可以使用DynamicData 属性来指定数据,驱动测试用例所用数据的成员的名称、种类(属性、默认值或方法)和定义类型(默认情况下使用当前类型)

代码实现

新建目标类DataChecker,增加待测试的方法,内容如下:

cs 复制代码
    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

cs 复制代码
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

符合预期结果

相关推荐
雨落倾城夏未凉10 小时前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫2 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫2 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6253 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902113 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠3 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫5 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech6 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf7 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6257 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#