Search code examples
asp.netasp.net-mvcmockingmoqhttpcontext

How to use microsoft fakes to Mock HttpSessionStateBase


Moq Code:

mockControllerContext.SetupGet(x => x.HttpContext.Session["User"]).Returns(new User
{
    Name = "Moto", 
    IsAdmin = true                                                                                        
});
taskController.ControllerContext = mockControllerContext.Object;

How can i use MS Fakes to Mock HttpContext.Session???


Solution

  • You can use shims for that with Microsoft Fakes. However, I find this to be a bad practice. Instead you should isolate yourself from third party libraries by wrapping them in your own class. Then you can put an interface on that class and use your interface throughout your code. This anti-corruption layer allows you to shield yourself from third party assemblies and you are less affected when the third party assembly changes.

    If you want to learn more about using shims, you can checkout this Pluralsight course I authored on Microsoft Fakes. (Full disclosure: I get royalties on this course, but it is a quick way to get up to speed)