2011-05-06 109 views
2

我做了一个帮手如何测试辅助方法?

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

如何创建试验所需的帮手?

回答

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