2013-02-11 76 views
3

我開始對將使用TDD在很大程度上寫了一個新的MVC應用程序開發的痛苦測試的MVC應用程序。我想添加一些集成測試,以確保完全有線的應用程序(我使用IOC的StructureMap,NHibernate的持久性)按預期工作。集成無UI自動化

雖然我打算寫硒幾個功能煙霧測試,可維護性的原因,我寧願做我最集成測試通過直接調用,使用好老的C#我的控制器動作。

有一個如何做到這一點少得驚人的指導,所以我花了刺攻擊

  1. 把所有啓動代碼出來的Global.asax,併成爲一個單獨的類
  2. 嘗試的計劃利用MvcContrib-TestHelper或類似創建ASP.NET依賴(上下文,請求等)

我已經完成第1步,但真的不知道如何繼續執行步驟2的任何指導,將不勝感激。

public class Bootstrapper 
{    
    public static void Bootstrap() 
    { 
     DependencyResolverInitializer.Initialize(); 
     FilterConfig.RegisterFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     ModelBinders.Binders.DefaultBinder = new SharpModelBinder(); 
    }   
} 

public class DependencyResolverInitializer 
{ 
    public static Container Initialize() 
    { 
     var container = new Container(); 
     container.Configure(x => x.Scan(y => 
     { 
      y.Assembly(typeof(Webmin.UI.FilterConfig).Assembly); 
      y.WithDefaultConventions(); 
      y.LookForRegistries(); 

     })); 

     DependencyResolver.SetResolver(new StructureMapDependencyResolver(container)); 
     return container; 
    } 
} 

public class StructureMapDependencyResolver : IDependencyResolver 
{ 
    private readonly IContainer _container; 

    public StructureMapDependencyResolver(IContainer container) 
    { 
     _container = container; 
    } 

    public object GetService(Type serviceType) 
    { 
     if (serviceType.IsAbstract || serviceType.IsInterface) { 
      return _container.TryGetInstance(serviceType); 
     } 
     return _container.GetInstance(serviceType); 
    } 

    public IEnumerable<object> GetServices(Type serviceType) 
    { 
     return _container.GetAllInstances(serviceType).Cast<object>(); 
    } 
} 

回答

4

如果你想要做的自動化ASP.NET MVC應用程序的終端到終端的測試無需通過UI去,一個好辦法做到這一點是編程發送HTTP請求到不同的URL並在之後聲明系統的狀態。

集成測試將基本上是這樣的:

  1. 安排:啓動Web服務器測試來承載Web應用程序
  2. 法:將HTTP請求發送到特定的URL,這將由控制器操作處理
  3. 聲明:驗證系統狀態(例如查找特定數據庫記錄)或驗證響應內容(例如,查看f或者在返回的HTML特定字符串)

您可以輕鬆地在進程 Web服務器,使用CassiniDev舉辦一個ASP.NET Web應用程序。此外,以編程方式發送HTTP請求的一種便捷方式是使用Microsoft ASP.NET Web API Client Libraries

下面是一個例子:

[TestFixture] 
public class When_retrieving_a_customer 
{ 
    private CassiniDevServer server; 
    private HttpClient client; 

    [SetUp]   
    public void Init() 
    { 
     // Arrange 
     server = new CassiniDevServer(); 
     server.StartServer("..\relative\path\to\webapp", 80, "/", "localhost"); 
     client = new HttpClient { BaseAddress = "http://localhost" }; 
    } 

    [TearDown] 
    public void Cleanup() 
    { 
     server.StopServer(); 
     server.Dispose(); 
    } 

    [Test] 
    public void Should_return_a_view_containing_the_specified_customer_id() 
    { 
     // Act 
     var response = client.GetAsync("customers/123").Result; 

     // Assert 
     Assert.Contains("123", response.Content.ReadAsStringAsync().Result); 
    } 
} 

如果你正在尋找這種技術的行動更完整的例子,你可以找到它在sample MVC 4 web application我的,我在那裏證明它寫下來的情況下automated acceptance tests