如何测试辅助方法?

时间:2011-05-06 13:08:55

标签: c# unit-testing asp.net-mvc-3 html-helper

我做了一个帮手

public static class UrlHelperExtension
{
    public static string GetContent(this UrlHelper url, string link, bool breakCache = true)
    {
        // stuff
    }
}

如何在单元测试中测试它?

[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?
    }
}

如何创建测试所需的助手?

3 个答案:

答案 0 :(得分:2)

如果你真的想测试它完全解耦,你必须引入另一层抽象。所以在你的情况下你可以这样做:

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);
    }
}

答案 1 :(得分:1)

阅读以下URl可能会对您有所帮助。 test the extension methods

答案 2 :(得分:0)

this website我想出了

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);
        }
    }
}