【Unit Test】測試監聽事件
/
0 Comments
紀錄監聽事件的測試。實作概念 : 檢查事件監聽者是否在事件被觸發後做出相對應的響應。
這個測試範例為當View接收到錯誤(事件)後去呼叫Logger去紀錄Log(監聽者)。
被測試程式碼如下:
測試程式碼 :
這個測試範例為當View接收到錯誤(事件)後去呼叫Logger去紀錄Log(監聽者)。
被測試程式碼如下:
public interface IView { event Action<string> ErrorOccured; } public interface ILogger { void LogError(string text); } public class Presenter { private readonly IView _view; private readonly ILogger _logger; public Presenter(IView view, ILogger logger) { this._view = view; this._logger = logger; this._view.ErrorOccured += ToLogError; } private void ToLogError(string text) { this._logger.LogError(text); } }
測試程式碼 :
private IView _View; private ILogger _Logger;[TestMethod()] public void PresenterTest_當View發生Error_呼叫寫Log() { this._View = Substitute.For<IView>(); this._Logger = Substitute.For<ILogger>(); Presenter p = new Presenter(this._View, this._Logger); //使用NSubstitute觸發ErrorOccured事件 this._View.ErrorOccured += Raise.Event<Action<string>>("error message"); //判斷監聽者是否做出正確的反應 this._Logger.Received() .LogError(Arg.Is<string>(x => x == "error message")); }