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

符合预期结果

相关推荐
阿松爱学习5 小时前
【Unity开发】监听Scene场景事件
unity·c#
2501_9159184111 小时前
在 Xcode 中运行和调试单元测试的完整指南
ide·vscode·macos·ios·单元测试·个人开发·xcode
天天代码码天天13 小时前
屏幕翻拍满是彩色条纹?用 C# + Vulkan 做了一个去摩尔纹工具,支持单图与文件夹批量
c#·去摩尔纹
2501_9307077814 小时前
使用C#代码在 Word 文档中添加、插入或删除页面
开发语言·c#·word
淡海水15 小时前
03-03-架构篇-SGen GC架构解析
unity·架构·c#·gc·sgen
曹牧1 天前
C#:输入的字符串格式不正确
c#
根号五1 天前
JetBrains Rider 使用教程(1)新建解决方案
c#·jetbrains rider
海天鹰1 天前
C#:接收从打开方式打开的参数
c#
极小狐2 天前
MR 里测试摘要空白、覆盖率不显示?JUnit 与覆盖率配置 9 步排查
数据库·ci/cd·junit·单元测试·mr·devops·代码覆盖率
宝桥南山2 天前
.NET 11 - 尝试一下Minimal API中的异步验证新特性
microsoft·微软·c#·asp.net·.net·.netcore