[英]Mock property and call method in same class C#
我有一個CommandExecutor類,其中包含所有命令(方法)。 我必須測試一種從給定2個參數生成報告的方法。 方法使用數據庫來檢查它是否已生成。
編輯1:
財產:
public IEngine Engine { get; set; }
IEngine界面:
ICommandExecutor CommandExecutor { get; }
IInputReader InputReader { get; }
IOutputWriter OutputWriter { get; }
IDatabase Database { get; }
CommandExecutor具有執行方法。 我還有其他創建ICommand的類(命令工廠)。 引擎從文件中讀取輸入,例如,檢查輸入是否有效,拆分參數等,並創建一個ICommand。 然后,CommandExecutor使用此ICommand並調用方法Execute。 Execute方法具有切換用例,如果成功或如果命令不成功,則每種情況都返回一個字符串,並拋出異常。 我想對依賴於數據庫的方法進行單元測試。 我可以模擬此屬性Engine(在CommandExecutor中)並調用方法以檢查其是否正常工作嗎? CommandExecutor中的每個方法都調用this.Engine.Database .....
引擎構造函數:
public Engine(
IInputReader reader,
IOutputWriter writer,
ICommandExecutor commandExecutor,
IDatabase database)
{
this.InputReader = reader;
this.OutputWriter = writer;
this.CommandExecutor = commandExecutor;
this.CommandExecutor.Engine = this;
this.Database = database;
}
var reportFound = this.Engine.Database.GetReport(name, model);
if (reportFound != null)
{
throw new DuplicateEntryException(Constants.Duplicate);
}
Do something......
return string.Format(Constants.Test, model, name);
我模擬了數據庫(也使用GetReport這種方法),使用模擬數據庫的引擎。 如何模擬CommandExecutor引擎屬性並調用要測試的方法?
謝謝
並非完全沒有,問自己為什么要這么做。 如果要保證類中的一個方法調用同一類中的另一個方法,那么聽起來好像業務邏輯封裝在其中,您不想繞過它。 將其重構為一個新類,並為該方法添加一個接口,將依賴關系注入其中,現在您可以模擬它了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.