close
在測試功能的時候,常常會需要寫類似BOT之類的工具或一些IDE的原生工具進行Unit Test,除了那些方式之外,C#可以透過映射(Reflection)的功能去自動列舉出所有某些特定條件的類別出來,減少手寫以及後續追加新類別的測試需要。
以下例來說,ICommand是所有測試指令的基礎介面,LoginCommand與LogoutCommand是實作的繼承類別
interface ICommand
{
void Todo();
}
class LoginCommand : ICommand
{
void Todo()
{
//...
}
}
class LogoutCommand : ICommand
{
void Todo()
{
//...
}
}
這時候就可以透過映射去自動找出所有ICommand的子類別並自動去生成與測試
foreach (Assembly assembly in System.AppDomain.CurrentDomain.GetAssemblies())
{
Type[] types = assembly.GetTypes();
Type targetType = typeof(ICommand);
foreach (Type type in types)
{
if (type.IsClass && type.IsSubclassOf(targetType))
{
ICommand cmd = Activator.CreateInstance(type) as ICommand;
string s = type.FullName;
...
cmd.Todo();
}
}
}
若後續有再新增繼承自ICommand的新功能,也會一併被加入測試而不需更改程式碼。
文章標籤
全站熱搜