c#单元测试
待测试项目:
namespace LambdaTest
{
class Program
{
static void Main(string[] args)
{
var fan = new DeskFan(new PowerSupply());
Console.WriteLine(fan.Work());
}
}
public interface IPowerSupply
{
int GetPower();
}
public class PowerSupply : IPowerSupply
{
public int GetPower()
{
return 170;
}
}
public class DeskFan
{
private IPowerSupply _powerSupply;
public DeskFan(IPowerSupply powerSupply)
{
_powerSupply = powerSupply;
}
public string Work()
{
int power = _powerSupply.GetPower();
if (power <= 120)
{
return "Low Voltage";
}
else if (power >= 200)
{
return "Over Voltage";
}
else
{
return "Fine Power";
}
}
}
}
单元测试步骤
右键点击Solution,选择Add,新项目:
选择Unit Test或xUnit Test:
填写项目名字,点击Create:
添加对待测试项目的引用:
选择项目:
编写单元测试代码:
namespace InterfaceExample_UnitTest
{
[TestClass]
public class TestExample
{
[TestMethod]
public void PowerLower()
{
var fan = new DeskFan(new PowerLowerExample());
var expected = "Low Voltage";
var actual = fan.Work();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void PowerHigher()
{
var fan = new DeskFan(new PowerHigherExample());
var expected = "Over Voltage";
var actual = fan.Work();
Assert.AreEqual(expected, actual);
}
class PowerLowerExample : IPowerSupply
{
int IPowerSupply.GetPower()
{
return 80;
}
}
class PowerHigherExample : IPowerSupply
{
int IPowerSupply.GetPower()
{
return 240;
}
}
}
}
打开Test Explore,查看,
右键点击case,Run,查看运行结果:
以上解决方案结构:
使用mork简化单元测试编写
mork可省略繁琐的类似下面的接口定义:
过程记录如下:
右键点击项目,选择Manage NuGet Packages
在Browse里搜索Moq:
选中,点击Install:
选择OK:
安装完毕:
回到测试项目中,修改代码: