简体   繁体   English

模拟方法被调用,但验证返回 false

[英]Mocked method being called, but Verify returns false

Using Moq, I have a method that is being called but the Verify in the test fails stating it isn't.使用 Moq,我有一个正在调用的方法,但测试中的验证失败,说明它不是。 Confused as it seems that there is one invocation in the mock object.令人困惑的是,模拟 object 中似乎有一个调用。 Stepping through debugging, the code makes it to the method in question.逐步调试,代码使其成为有问题的方法。

the code in the test测试中的代码

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

the code that is being called被调用的代码

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

模拟对象的调试视图 测试输出

Appreciate any guidance感谢任何指导

Ok, thanks in part to @canton7 I figured it out.好的,部分感谢@canton7 我想通了。 Had to do some searching, but figured out how.不得不做一些搜索,但想出了如何。

The Verify needed to take any type of Exception and then I can check the property there. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM