I have a BaseController which all my controllers derive from, which sets a value (the user's nick name) in the ViewBag. I've done this so that I can have access to that value in the layout without having to implicitly set it for every controller (if you'd just suggest a better way to do this, go ahead!).
public class BaseController : Controller
{
public BaseController()
{
InitialiseViewBag();
}
protected void InitialiseViewBag()
{
ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());
ViewBag.NickName = user?.NickName;
}
}
I then derive that class, for example, in the HomeController:
public class HomeController : BaseController
{
private readonly IRoundRepository _repository = null;
public HomeController(IRoundRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View();
}
}
I've set up my controller's other dependency (the repository, used in another view not shown here) to come in on the constructor, and am using StructureMap for DI, and that's all working great WHEN I take out the line in the BaseController for getting the nick name.
The problem is when I include that line to get the nick name using the OWIN Context, my test fails with this
System.InvalidOperationException: No owin.Environment item was found in the context.
This is my test as of now:
[TestMethod]
public void HomeControllerSelectedIndexView()
{
// Arrange
HttpContext.Current = _context;
var mockRoundRepo = new Mock<IRoundRepository>();
HomeController controller = new HomeController(mockRoundRepo.Object);
// Act
ViewResult result = controller.Index() as ViewResult;
// Assert
Assert.IsNotNull(result);
}
I think I understand WHY it's not working, but I can't work out how to get around it.
How should I be mocking/injecting/otherwise setting up this base controller so it can access the user's identity and not fall over during my testing?
Note: I'm quite new to using dependency injection, so if it's something obviously, or I'm going about this completely wrong, or leaving out any important information, I won't be surprised!
Aucun commentaire:
Enregistrer un commentaire