How to mock the Request.ServerVariables using MOQ for ASP.NET MVC?
- by melaos
hi guys,
i'm just learning to put in unit testing for my asp.net mvc when i came to learn about the mock and the different frameworks there is out there now.
after checking SO, i found that MOQ seems to be the easiest to pick up.
as of now i'm stuck trying to mock the Request.ServerVariables, as after reading this post, i've learned that it's better to abstract them into property.
as such:
/// <summary>
/// Return the server port
/// </summary>
protected string ServerPort
{
get
{
return Request.ServerVariables.Get("SERVER_PORT");
}
}
But i'm having a hard time learning how to properly mock this.
I have a home controller ActionResult function which grabs the user server information and proceed to create a form to grab the user's information.
i tried to use hanselman's mvcmockhelpers class but i'm not sure how to use it.
this is what i have so far...
[Test]
public void Create_Redirects_To_ProductAdded_On_Success()
{
FakeViewEngine engine = new FakeViewEngine();
HomeController controller = new HomeController();
controller.ViewEngine = engine;
MvcMockHelpers.SetFakeControllerContext(controller);
controller.Create();
var results = controller.Create();
var typedResults = results as RedirectToRouteResult;
Assert.AreEqual("", typedResults.RouteValues["action"], "Wrong action");
Assert.AreEqual("", typedResults.RouteValues["controller"], "Wrong controller");
}
Questions:
As of now i'm still getting null
exception error when i'm running the
test. So what am i missing here?
And if i use the mvcmockhelpers
class, how can i still call the
request.verifyall function to ensure
all the mocking are properly setup?