kformeck
kformeck

Reputation: 1823

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

I would like to verify that when AuthenticateUserAsync() (which has a return type of void) is called that the appropriate action is raised.

Here my current approach:

var mock = new Mock<ILoginPresenter>();
mock.Setup(x => x.AuthenticateUserAsync(username, password))
    .Raises(x => x.UserPassesAuthentication += null, new LoginEventArgs(thing));

The problem is that when this test runs, I get an error:

Could not locate event for attach or detach method Void set_UserPassesAuthentication(System.Action`1[Common.View.LoginEventArgs]).

It seems like I'm having issues with .Raises call on an action instead of an event.

Any suggestions?

Edit

Here is the definition for the 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);
}

Upvotes: 0

Views: 453

Answers (1)

Nkosi
Nkosi

Reputation: 247098

.Raises is used for events. you are trying to call it with an Action<T> which will not work. you need to mock the action and call it in a call back from the AuthenticateUserAsync setup

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

Upvotes: 1

Related Questions