遇到流程一樣,但是處理邏輯不一樣的狀況,可利用 Template Pattern 樣板模式
建立一個 UnitFlowBase 抽像類別提供框架,裡面有三個方法
Node1 (每個測試類別只都執行一次)
Node2 (每次執行測試方法時都執行一次)
....
UnitTest (執行測試方法,裡面通常會執行多個 UnitFlowBase 提供的方法
所以才會說 UnitFlowBase 提供框架,例如:此範例 UnitTest 執行了 Node2() 與 Node3())
public abstract class UnitFlowBase
{
protected UnitFlowBase()
{
Node1();
}
protected virtual void Node1()
{
}
protected virtual void Node2()
{
}
protected abstract bool Node3();
public void UnitTest()
{
Node2();
Console.WriteLine(Node3() ? "Assert Successful." : "Assert Fail.");
}
}
建立 UnitCounter1 與 UnitCounter2
Execute方法 顯示目前 ClassCount 跟 MethodCount 執行次數
public class UnitCounter1 : UnitFlowBase
{
private int _classCounter = 0;
private int _methodCounter = 0;
protected override void Node1()
{
_classCounter++;
}
protected override void Node2()
{
_methodCounter++;
}
protected override bool Node3()
{
Console.WriteLine($"ClassCounter1 : {_classCounter}");
Console.WriteLine($"MethodCounter1: { _methodCounter}");
return true;
}
}
public class UnitCounter2 : UnitFlowBase
{
private int _classCounter = 0;
private int _methodCounter = 0;
protected override void Node1()
{
_classCounter += 2;
}
protected override void Node2()
{
_methodCounter += 2;
}
protected override bool Node3()
{
Console.WriteLine($"ClassCounter2 : {_classCounter}");
Console.WriteLine($"MethodCounter2: { _methodCounter}");
return true;
}
}
建立一個 UnitCounter1 與 UnitCounter2 類別,各執行二次 UnitTest 方法
class Program
{
static void Main(string[] args)
{
UnitCounter1 unit1_ = new UnitCounter1();
UnitCounter2 unit2_ = new UnitCounter2();
unit1_.UnitTest();
unit1_.UnitTest();
unit2_.UnitTest();
unit2_.UnitTest();
}
}
執行結果:
ClassCount : 1
MethodCount : 1
Assert Successfull.
ClassCount : 1
MethodCount : 2
Assert Successfull.
ClassCount : 2
MethodCount : 2
Assert Successfull.
ClassCount : 2
MethodCount : 4
Assert Successfull.