2016-09-15 24 views
0

我想驗證何時調用AuthenticateUserAsync()(它具有void的返回類型),以引發相應的操作。如何在調用方法時驗證是否引發了操作(使用Moq進行單元測試)

這裏我目前的做法:

var mock = new Mock<ILoginPresenter>(); 
mock.Setup(x => x.AuthenticateUserAsync(username, password)) 
    .Raises(x => x.UserPassesAuthentication += null, new LoginEventArgs(thing)); 

的問題是,當這個測試運行,我得到一個錯誤:

Could not locate event for attach or detach method Void set_UserPassesAuthentication(System.Action`1[Common.View.LoginEventArgs]). 

好像我在與.Raises問題的呼籲一個行動而不是一個事件。

有什麼建議嗎?

編輯

下面是ILoginPresenter定義:

public interface ILoginPresenter 
{ 
    Action<LoginEventArgs> UserPassesAuthentication { get; set; } 
    Action UserFailedAuthentication { get; set; } 
    void AuthenticateUserAsync(string user, string password); 
    bool IsLoginFabVisible(int userTextCount, int passwordTextCount); 
} 
+0

回你可以顯示'ILoginPresenter' – Nkosi

+0

@Nkosi代碼定義發佈 – kformeck

+0

'.Raises'用於事件。你試圖用一個不起作用的動作來調用它。您需要模擬該操作並在來自'AuthenticateUserAsync'設置的回調中調用它 – Nkosi

回答

1

.Raises用於事件。您正嘗試使用Action<T>來調用它,這將不起作用。您需要模擬行動,並在通話中調用它從AuthenticateUserAsync設置

Action<LoginEventArgs> handler = args => { 
    //...action code; 
}; 

var mock = new Mock<ILoginPresenter>(); 
mock.Setup(x => x.UserPassesAuthentication(It.IsAny<Action<LoginEventArgs>Action<LoginEventArgs>>())) 
    .Returns(handler); 
mock.Setup(x => x.AuthenticateUserAsync(username, password)) 
    .Callback(handler(new LoginEventArgs(thing))); 
相關問題