C# 使用MSTest进行单元测试

发表于:2024-3-04 09:30

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:rjcql    来源:CSDN

  写在前面
  MSTest是微软官方提供的.NET平台下的单元测试框架;可使用DataRow属性来指定数据,驱动测试用例所用到的值,连续对每个数据化进行运行测试,也可以使用DynamicData 属性来指定数据,驱动测试用例所用数据的成员的名称、种类(属性、默认值或方法)和定义类型(默认情况下使用当前类型)。
  代码实现
  新建目标类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 });
      }
  }
  执行结果
  打开命令行窗口执行以下命令:
  dotnet test
   符合预期结果。
  本文内容不用于商业目的,如涉及知识产权问题,请权利人联系51Testing小编(021-64471599-8017),我们将立即处理
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号