Mocking a signed in Identity User

I am using Moq and xUnit to create unit tests. However, because of the way my action methods are set up, I'm having a hard time doing so. In my controller, I use

var user = await userManager.FindByNameAsync(User.Identity.Name);

to get the the signed in user information. I used this approach to avoid the number of parameters Is there a way to mock this in a unit test, or should the controller be set up differently?

The AppUser class extends IdentityUser for specific properties that are used within the controller.

1 answer

  • answered 2018-02-13 01:37 Jaliya Udagedara

    For mocking above you can do something like following,

    Mock<UserManager<User>> userManagerMock = new Mock<UserManager<User>>();
    userManagerMock
        .Setup(m => m.FindByNameAsync(It.IsAny<string>()))
        .Returns(Task.FromResult(It.IsAny<User>()));
    

    Please note I haven't compiled this code, but you should be able to get the idea.