How do I test a helper method?
I've made a helper
public static class UrlHel开发者_JS百科perExtension
{
public static string GetContent(this UrlHelper url, string link, bool breakCache = true)
{
// stuff
}
}
How do I test it in a unit test?
[TestClass]
public class HelperTestSet
{
[TestMethod]
public void GetContentUrl()
{
// What do I need to do here?
// I need a RequestContext to create a new UrlHelper
// Which is the simplest way to test it?
}
}
How do I create the helper needed for the test?
If you really want to test it totally uncoupled, you have to introduce another layer of abstraction. So in your case you could do something like this:
public interface IUrlHelper
{
public string Action(string actionName);
// Add other methods you need to use in your extension method.
}
public class UrlHelperAdapter : IUrlHelper
{
private readonly UrlHelper urlHelper;
public UrlHelperAdapter(UrlHelper urlHelper)
{
this.urlHelper = urlHelper;
}
string IUrlHelper.Action(string actionName)
{
return this.urlHelper.Action(actionName);
}
}
public static class UrlHelperExtension
{
public static string GetContent(this UrlHelper url, string link, bool breakCache = true)
{
return GetContent(new UrlHelperAdapter(url), link, breakCache);
}
public static string GetContent(this IUrlHelper url, string link, bool breakCache = true)
{
// Do the real work on IUrlHelper
}
}
[TestClass]
public class HelperTestSet
{
[TestMethod]
public void GetContentUrl()
{
string expected = "...";
IUrlHelper urlHelper = new UrlHelperMock();
string actual = urlHelper.GetContent("...", true);
Assert.AreEqual(expected, actual);
}
}
Read the following URl may help you. test the extension methods
From this website I came up with
namespace Website.Tests
{
public static class UrlHelperExtender
{
public static string Get(this UrlHelper url)
{
return "a";
}
}
[TestClass]
public class All
{
private class FakeHttpContext : HttpContextBase
{
private Dictionary<object, object> _items = new Dictionary<object, object>();
public override IDictionary Items { get { return _items; } }
}
private class FakeViewDataContainer : IViewDataContainer
{
private ViewDataDictionary _viewData = new ViewDataDictionary();
public ViewDataDictionary ViewData { get { return _viewData; } set { _viewData = value; } }
}
[TestMethod]
public void Extension()
{
var vc = new ViewContext();
vc.HttpContext = new FakeHttpContext();
vc.HttpContext.Items.Add("wtf", "foo");
var html = new HtmlHelper(vc, new FakeViewDataContainer());
var url = new UrlHelper(vc.RequestContext);
var xx = url.Get();
Assert.AreEqual("a", xx);
}
}
}
精彩评论