dimanche 24 juillet 2016

Mocking IPrincipal in ASP.NET Core

I have an ASP.NET MVC Core application that I am writing unit tests for. One of the action methods uses User name for some functionality:

SettingsViewModel svm = _context.MySettings(User.Identity.Name);

which obviously fails in the unit test. I looked around and all suggestions are from .NET 4.5 to mock HttpContext. I am sure there is a better way to do that. I tried to inject IPrincipal, but it threw an error; and I even tried this (out of desperation, I suppose):

public IActionResult Index(IPrincipal principal = null) {
    IPrincipal user = principal ?? User;
    SettingsViewModel svm = _context.MySettings(user.Identity.Name);
    return View(svm);
}

but this threw an error as well. Couldn't find anything in the docs either...

Aucun commentaire:

Enregistrer un commentaire