假设场景
电扇依赖于电源,电源电流值不同电扇工作效果不同
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
var power = new PowerSupply();
var fan = new DeskFan(power);
Console.WriteLine(fan.Work());
}
}
class PowerSupply
{
public int GetPower()
{
return 210;
}
}
class DeskFan
{
private PowerSupply _powerSupply;
public DeskFan(PowerSupply powerSupply)
{
_powerSupply = powerSupply;
}
public string Work()
{
int power = _powerSupply.GetPower();
if (power <= 0)
{
return "Won't Work";
}
else if (power < 100)
{
return "Slow";
}
else if (power < 200)
{
return "Work fine";
}
else
{
return "Warning!";
}
}
}
}
可以看出,此时如果想测试风扇的工作情况,就必须去PowerSupply类内部提供电源的方法中去修改代码,而一个类设计好之后不应该再去修改代码的。就比如说这个场景下不止是风扇连接着电池,而还有设备也连接着。为了测试风扇而更改代码很可能会导致其他设备出故障。
引入接口,进行解耦,再使用单元测试
为了解决上面的测试问题,我们抽象出了一个电源提供接口,写一个测试类实现电源提供接口,专门用来测试电源电力大小对风扇造成的影响:
namespace TestClass
{
class Program
{
static void Main(string[] args)
{
var fan = new DeskFan(new TestPowerSupply());
fan.Work();
Console.ReadKey();
}
}
public interface IPowerSupply
{
int GetPower();
}
public class PowerSupply:IPowerSupply
{
public int GetPower()
{
return 100;
}
}
public class TestPowerSupply : IPowerSupply
{
public int GetPower()
{
return 100000;
}
}
public class DeskFan
{
private IPowerSupply _powerSupply;
public DeskFan(IPowerSupply powerSupply)
{
_powerSupply = powerSupply;
}
public string Work()
{
int power = _powerSupply.GetPower();
if(power<=0)
{
return "Wont't work";
}
else
{
return "Working";
}
}
}
}
要测试的话,我们可以使用单元测试进行调试。新建一个单元测试
namespace TestClassTests
{
public class UnitTest1
{
[Fact]
public void PowerLowerThanZero_OK()
{
var mock = new Mock<IPowerSupply>();
mock.Setup(s=>s.GetPower()).Returns(()=>0);
var fan = new DeskFan(new PowerSupplyThanZero(0));
var test= fan.Work();
Assert.Equal("",test);
var mock = new Mock<IPowerSupply>();
mock.Setup(s => s.GetPower()).Returns(() => 0);
var fan = new DeskFan(mock.Object);
var test = fan.Work();
Assert.Equal("", test);
}
}
public class PowerSupplyThanZero : IPowerSupply
{
private int _power;
public PowerSupplyThanZero(int power)
{
_power = power;
}
public int GetPower()
{
return _power;
}
}
}
这样的测试方法进很正规了,不会影响到其他模块。
|