[英]How to configure unit tests with an IoC container in ASP.NET?
我已經在ASP.NET應用程序中配置了Unity,並在Application_BeginRequest中收到第一個請求時加載了配置。 然后將Unity容器作為屬性存儲在Global.ascx中,以便我的其他類可以訪問它:
public static IUnityContainer ContainerHolder { get; set; }
IUnityContainer IContainerAccessor.Container
{
get { return ContainerHolder; }
}
ContainerHolder,在整個應用程序中保存容器實例,並且Container屬性允許在每個會話中訪問此屬性。
然后,我有了一個UnityLocator類,使我可以在整個應用程序中訪問此屬性:
public static class UnityLocator
{
private static IUnityContainer Container
{
get
{
return ((IContainerAccessor)HttpContext.Current.ApplicationInstance).Container;
}
}
}
一切正常!
我還有一種從Unity訪問實例的方法:
UnityLocator.GetInstance<IThemeManager>();
protected Repository(ICustomCacheManager customCacheManager)
{
this.Cache = customCacheManager;
}
protected Repository()
: this(UnityLocator.GetInstance<ICustomCacheManager>())
{
}
它已在我的應用程序中使用過,以便我可以從Unity中檢索現有實例,以便將其注入到其他類中。 例如,我的視圖(asp.net頁)將其作為依賴項注入到Presenter類中。
現在,我想配置單元測試以運行。
我該怎么辦? global.ascx顯然不存在,所以我認為我應該創建一個BaseTest類並讓所有測試繼承它。 然后在這個BaseTest類的構造函數中,建立我的實例。 這是正確的方法嗎?
現在如何使用Unity配置單元測試?
謝謝
更新:UnityLocator.GetInstance已添加。
您不必擔心訪問IoC容器。 這違反了單元測試。
單元測試您不必擔心任何具體的實現或依賴關系(被測類除外)。
對我來說,在全球范圍內提供IoC是一個糟糕的設計選擇。 您應該通過屬性或構造函數注入依賴項。
可能使用全局應用程序類來存儲服務定位器不是一個好主意。 為什么不使用內置的ServiceLocator類? 它可以在代碼中的任何位置使用,並且不依賴於全局應用程序/ HttpContext。
是否在單元測試中使用容器是另一回事。 就個人而言,只要您將服務的存根實現放入容器中,我就不會反對。
編輯:使用ServiceLocator配置容器的方式:
private void ConfigureUnity()
{
UnityServiceLocator locator = new UnityServiceLocator( ConfigureUnityContainer() );
ServiceLocator.SetLocatorProvider( () => locator );
}
private IUnityContainer ConfigureUnityContainer()
{
IUnityContainer container = new UnityContainer();
// this loads container's configuration, comment or uncomment
container.LoadConfiguration();
return container;
}
然后,您可以從定位器中訪問容器,例如:
var container = ServiceLocator.Current.GetInstance<IUnityContainer>();
在您的頁面中,嘗試執行以下操作:
public class DepartmentReportPage : Page
{
private readonly DepartmentReportPresenter _presenter;
public DepartmentReportPage()
{
this._presenter =
UnityLocator.GetInstance<DepartmentReportPresenter>();
this._presenter.View = this;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.