[英]Mocked method being called, but Verify returns false
使用 Moq,我有一個正在調用的方法,但測試中的驗證失敗,說明它不是。 令人困惑的是,模擬 object 中似乎有一個調用。 逐步調試,代碼使其成為有問題的方法。
測試中的代碼
[Fact]
public async Task WhenUsernameAndPasswordAreEmpty_ThenDisplayErrorMessage() {
mockAuthenticationService.Setup(mock => mock.SignInAsync(It.IsAny<string>(), It.IsAny<string>())).Throws(new NullReferenceException());
var loginMessageReceived = false;
mockAppService.Setup(mock => mock.IsBusy).Returns(false);
mockLoginViewModel.Object.Username = string.Empty;
mockLoginViewModel.Object.Password = string.Empty;
MessagingCenter.Subscribe<LoginViewModel>(this, "LoginSuccessful", (obj) => {
loginMessageReceived = true;
});
await mockLoginViewModel.Object.LoginCommand.ExecuteAsync();
Equals(loginMessageReceived, false);
mockAuthenticationService.Verify(auth => auth.SignInAsync(string.Empty, string.Empty), Times.Once());
mockMessageService.Verify(msg => msg.DisplayLoginError(new Exception("You must enter both a username and password to login.")), Times.Once());
}
被調用的代碼
catch (NullReferenceException ex) {
_messageService.DisplayLoginError(new Exception("You must enter both a username and password to login."));
var properties = new Dictionary<string, string> {
{ "ExecuteLoginCommand", "You must enter both a username and password to login." },
{ "Username", Username },
{ "Password", Password }
};
Crashes.TrackError(ex, properties);
}
感謝任何指導
好的,部分感謝@canton7 我想通了。 不得不做一些搜索,但想出了如何。
Verify
需要采取任何類型的Exception
,然后我可以在那里檢查屬性。
mockMessageService.Verify(msg =>
msg.DisplayLoginError(It.Is<Exception>(ex =>
ex.Message == "You must enter both a username and password to login."
))
, Times.Once()
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.