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:

安裝完畢:

回到測驗專案中,修改代碼:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/190008.html
標籤:其他
上一篇:工業樹莓派新品:不僅功能更強大、緊湊,價格也很有優勢!!
下一篇:javacv進階videoinput:使用videoinput獲取攝像機串列并預覽攝像機影像畫面(只支持windows)
