Shaggy13spe
Shaggy13spe

Reputation: 733

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. Confused as it seems that there is one invocation in the mock 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);
 }

debug view of mock object test output

Appreciate any guidance

Upvotes: 1

Views: 403

Answers (1)

Shaggy13spe
Shaggy13spe

Reputation: 733

Ok, thanks in part to @canton7 I figured it out. 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.

mockMessageService.Verify(msg => 
    msg.DisplayLoginError(It.Is<Exception>(ex => 
        ex.Message == "You must enter both a username and password to login."
    ))
    , Times.Once()
);

Upvotes: 2

Related Questions