mercredi 29 juin 2016

Mock ApplicationUserManager for Unit Testing MVC controllers

I would like to know if someone can help me with this.

I am writing unit tests for a specific controller. That controller inherits from a BaseController and that BaseController has this property:

private ApplicationUserManager userManager;
public ApplicationUserManager UserManager 
{ 
    get { return this.userManager ??  this.Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); } 
    set { this.userManager = value; } 
}

The ctor for ApplicationUserManager is:

public ApplicationUserManager(IUserStore<ApplicationUser> store, IIdentityMessageService emailService)
        : base(store)
    {
        this.EmailService = emailService;

        var dataProtectionProvider = Startup.DataProtectionProvider;
        this.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
    }

This is what I am doing to mock the ApplicatonUserManager class:

var store = new Mock<IUserStore<ApplicationUser>>();
var emailService = new Mock<IIdentityMessageService>();
var applicationUserManager = new Mock<ApplicationUserManager>(store.Object, emailService.Object);
this.targetController.UserManager = applicationUserManager.Object;
var dataprotectionprovided = new Mock<IDataProtectionProvider>();
applicationUserManager.Setup(r => r.UserTokenProvider).Returns(new DataProtectorTokenProvider<ApplicationUser, string>(dataprotectionprovided.Object.Create("ASP.NET Identity")));
this.targetController.UserManager = applicationUserManager.Object;

I have tried to mock this but because this is not virtual property (UserTokenProvider) it does not allow me and I get this exception:

System.NotSupportedException: Invalid setup on a non-virtual (overridable in VB) member: r => r.UserTokenProvider

Can anyone help me with this problem? I just want to mock this in order to test the controller that inherits from a BaseController that has that property..

Thanks

Aucun commentaire:

Enregistrer un commentaire