[英]how to skip constructor call from unit test?
我正在為類方法“ Execute”之一執行單元測試,但不想執行類構造函數代碼。
有什么方法可以跳過單元測試執行中的構造函數代碼調用?
班級代碼,
public class DemoCls
{
public DemoCls()
{
string ConfigFolderPath = Path.Combine(Environment.CurrentDirectory, @"\Config");
//string dataFolder = @"C:\Data1";
foreach (string X in Directory.EnumerateFiles(ConfigFolderPath, "test" + "*.xml"))
{
}
}
public void Execute()
{
}
}
單元測試代碼,
[TestClass()]
public class DemoClsTests
{
[TestMethod()]
public void ExecuteTest()
{
var X = new DemoCls();
X.Execute();
}
}
重寫類,這是兩種方法之一:
使用接口(可以在單元測試中模擬)將信息傳遞到構造函數中
public interface IConfigFiles { List<string> Files { get; set; } } public DemoCls(IConfigFiles files) { }
從構造函數中刪除配置代碼,然后將其放在其他函數中。
public DemoCls() { // does nothing } public void Setup() { string ConfigFolderPath = Path.Combine(Environment.CurrentDirectory, @"\\Config"); //... }
接口更適合單元測試。
“有沒有辦法從單元測試執行中跳過構造函數代碼的調用?”
答案是:否(例如方法)
您可以將ctor代碼包裝在“ if”預處理程序指令中,並僅在非測試運行期間有條件地執行它。
#define DEBUG
// ...
#if DEBUG
Console.WriteLine("Debug version");
#endif
看到
您可以使用一個單元測試框架,該框架允許您模擬具體的類,以便在沒有接口的情況下偽造一個類,例如,我正在使用Typemock隔離器,並且我可以模擬幾乎任何類,並確定所有類的情況成員及其構造函數。 這是您所遇到的課程的測試:
[TestMethod,Isolated]
public void TestMethod()
{
var fake = Isolate.Fake.Instance<DemoCls>(Members.CallOriginal, ConstructorWillBe.Ignored);
fake.Execute();
Isolate.Verify.WasCalledWithAnyArguments(() => fake.Execute());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.