Chorn Sokun's Weblog

Conquer inner fear, push it to the limit!

Mocking ASP.NET MVC 2 Context & Session using RhinoMock

leave a comment »

Watching video record from #mvcconf about “Making ASP.NET Apps Testable” by Eric B. Sowell. He showing how to test ASP.NET MVC Session make me wonder how difficult it is for RhinoMock so I load sample app and here how I test it. Since

[Test]
public void TestSession()
{
   // Arrange
   // HttpContextBase, HttpSessionStateBase are abstract classes
   // I can ask RhinoMock to generate stubs for those classes
   var httpContext = MockRepository.GenerateStub<HttpContextBase>();
   var session = MockRepository.GenerateStub<HttpSessionStateBase>();

   session["Name"] = "Sokun";
   httpContext.Stub(c => c.Session)
      .Return(session);

   // act
   controller.ControllerContext = new ControllerContext(httpContext, new RouteData(), controller);
   var result = controller.TestSession() as ViewResult;

   // assert
   Assert.IsNotNull(result);
}

and the action:

public ActionResult TestSession()
{
   ViewData["Name"] = Session["Name"];
   return View();
}

So, what you think? it just fine to love ASP.NET MVC 2

Advertisements

Written by Chorn Sokun

July 26, 2010 at 10:45 am

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: