WiredWorx || Web design || SEO || Bournemouth
Web design, website development and search engine optimisation (SEO) in Bournemouth, Dorset, UK.
Home ·
Website and SEO · C# tutorials and tips · Create a mock session in ASP.NET MVC using Rhino Mocks
Create a mock session in ASP.NET MVC using Rhino Mocks
11.02.2011. 12:22
Firstly we will introduce a few of the objects:
_testRepository
=> is a repository which implements the same interface as the controller we are putting to test.
_controller
r => is the controller we are testing, which has an over-ridden constructor passing in the _testRepository.
_mockRepository
=> is a Rhino.Mocks class to create the mock data which we will be using.
The process is then fairly simple (although took about a day's worth of work to figure out!)
The first block of code is used to create the HttpSessionStateBase object and then create a stub which in effect is the mocked session variable and value.
The second block is where we create the HttpContextBase object, as the session needs to live in the context this step is necessary. There are also other elements of the context which may be mocked as well (such as request, response etc) but for this example we're not worried about them. We then set it so that when a session is requested from the calling code, the object will return the session mock that we just created.
The third block of code was what baffled me for a while! I am still not 100% sure what it is doing, but it seems that in order for these objects to be accessible to calling code they must be set into a 'Replay' state.
Finally we set the ControllerContext of our controller to be the mock context we have just set up... Et voila, the session variables that are set up are now accessible from the unit tests!