C#单元测试用例的使用方法

当我们写好一段代码后,我们不能一直在这段代码集中写实行的例子,需要自己构建单元测试用例,操作步骤如下:

在解决方案中新建项目

使用xunit这个工具来建立单元测试。

这里写一段机器内部依靠电池供电量来运转的情况。

using System;

namespace UnitTestExample
{
   public class Program
    {
        static void Main(string[] args)
        {
            DeskFan desk = new DeskFan(new engine());
            Console.WriteLine(desk.Work());
        }
    }
    public interface IPowerSupply
    {
        int PowerSupply();
    }
    public class engine : IPowerSupply
    {
        public int PowerSupply()
        {
            return 110;
        }
    }
    public class sumsang : IPowerSupply
    {
        public int PowerSupply()
        {
            return 220;
        }
    }
    public class DeskFan
    {
        private IPowerSupply _powersupply;
        public DeskFan(IPowerSupply powersupply)
        {
            _powersupply = powersupply;
        }
        public string Work()
        {
            int power = _powersupply.PowerSupply();
            if (power <= 0)
            {
                return "Won't work";
            }else if (power<100){
                return "Slow";
            }else if (power < 200)
            {
                return "Work fine";
            }
            return "warning!";
        }
    }

}

单元测试构建如下

using System;
using Xunit;
using UnitTestExample;
using Moq;

namespace XUnitTestProject
{
    public class UnitTest1
    {
        [Fact]
        public void Test1()
        {
            var desk = new DeskFan(new powerlowerthan());
            var target = "Won't work";
            var actual = desk.Work();
            Assert.Equal(target, actual);
        }
        [Fact]
        public void Test2()
        {
            var Mock = new Mock<IPowerSupply>();
            Mock.Setup(ps => ps.PowerSupply()).Returns(() => 200);
            var desk = new DeskFan(Mock.Object);
            var target = "warning!";
            var actual = desk.Work();
            Assert.Equal(target, actual);
        }
    }
    public class powerlowerthan : IPowerSupply
    {
        public int PowerSupply()
        {
            return 0;
        }
    }

}

可以看到有两种写法,第一种是自己写类去进行测试,另外一种是根据工具Moq来自己创建测试类,推荐使用Moq,比较简洁。

Moq下载方式:右键解决方案->管理解决方案的Nuget程序包,然后在里面搜索Moq,安装即可。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值