簡體   English   中英

如何在調用方法時驗證是否引發了操作(使用Moq進行單元測試)

[英]How do I verify that an action is raised when calling a method (unit testing with Moq)

我想驗證在調用AuthenticateUserAsync()(返回類型為void)時是否引發了適當的操作。

這是我目前的做法:

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);
}

.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)));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM