I wrote some extensions to the MVC helpers. The problem is that I do not know how to do to test these methods since I do not have these objects in a test drive.
How do I test the methods I've created?
I wrote some extensions to the MVC helpers. The problem is that I do not know how to do to test these methods since I do not have these objects in a test drive.
How do I test the methods I've created?
To get these helpers you need to instantiate them. One practical way is to have a class with static properties, so you can quickly get a helper in the context of your test.
public static class Helpers
{
internal static AjaxHelper<dynamic> AjaxHelper
{
get
{
return new AjaxHelper<dynamic>(
new ViewContext { HttpContext = new FakeHttpContext() },
new FakeViewDataContainer()
);
}
}
internal static HtmlHelper<dynamic> HtmlHelper
{
get
{
return new HtmlHelper<dynamic>(
new ViewContext { HttpContext = new FakeHttpContext() },
new FakeViewDataContainer()
);
}
}
internal static UrlHelper UrlHelper
{
get
{
return new FakeUrlHelper(
new RequestContext(new FakeHttpContext(), new RouteData())
);
}
}
}
Note that I'm creating the above objects with "false" classes, in English called mocks . Because there is no Http context in a unit test you need to create a fake context.
To implement these mocks just inherit from the base classes:
HttpContextBase:
internal class FakeHttpContext : HttpContextBase
{
// exemplo de implementação de Items, note o override
private Dictionary<object, object> _items = new Dictionary<object, object>();
public override IDictionary Items { get { return _items; } }
// caso você precise acessar o Request, você precisa de um mock para ele
public override HttpRequestBase Request { get { return new FakeHttpRequest(); } }
public override object GetService(Type serviceType)
{
return null;
}
}
HttpRequestBase:
internal class FakeHttpRequest : HttpRequestBase
{
public override Uri Url { get { return new Uri("http://www.exemplo.com/"); } }
public override string MapPath(string virtualPath)
{
return System.IO.Path.Combine(@"C:\temp", virtualPath.Replace("~/", "").Replace("/", "\"));
}
public override string ApplicationPath { get { return "/"; } }
}
IViewDataContainer:
internal class FakeViewDataContainer : IViewDataContainer
{
private ViewDataDictionary _viewData = new ViewDataDictionary();
public ViewDataDictionary ViewData {
get { return _viewData; }
set { _viewData = value; }
}
}
mocks above you can implement a test and use things like:
Helpers.UrlHelper.RequestContext.HttpContext.Request.MapPath("~/arquivo.js");
Helpers.UrlHelper.Content("");
Helpers.HtmlHelper.ViewContext.HttpContext.Items.Add("x", 1);
Helpers.AjaxHelper.ActionLink("Link", "Action", "Controller");
And if you need more methods just do overrides .