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

符合预期结果

相关推荐
czhc11400756637 小时前
7.29:树形;
c#
cm04Z9c917 小时前
C#摸鱼实录——IoC与DI案例详解
开发语言·c#
Python私教12 小时前
Codex 写出的代码能跑却算错钱:我用 3 个测试拆穿一次 AI 编程幻觉
python·单元测试·ai编程
geovindu13 小时前
CSharp:Chain of Responsibility Pattern
开发语言·后端·设计模式·c#·.net·责任链模式·行为模式
颜x小15 小时前
[C#]泛型类与泛型方法
开发语言·c++·c#
caishenzhibiao15 小时前
顺势交易矩阵主图 同花顺期货通指标
java·c语言·c#
TDengine (老段)16 小时前
TDengine Node.js 与 C# 连接器 — Web 服务与 .NET 集成
大数据·数据库·node.js·c#·.net·时序数据库·tdengine
河西石头17 小时前
再谈C#的抽象类和接口:从“适配器”到“毛坯房”的设计哲学
开发语言·c#·接口·依赖注入·抽象类·依赖倒挂
颜x小17 小时前
[C#]——接口与继承
开发语言·c++·c#
颜x小1 天前
[C#] C++与c#语法对比
开发语言·c++·c#