使用Moq,我有一个被调用的方法,但是测试中的Verify失败,说明不是。似乎很困惑,模拟对象中只有一个调用。逐步调试,代码将其转到有问题的方法中。
测试中的代码
[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);
}
赞赏任何指导
答案 0 :(得分:2)
好吧,部分感谢@ 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()
);