2009-11-24 62 views
2

我有一個像這樣如何嘲笑container.Resolve <Type>()

public class HomeController 
{ 
    public ActionResult Index() 
    { 
     var x = Container.Resolve<IOrganisationService>(); 
    } 
} 

當單元測試,我得到一個空引用異常當容器試圖解決
任何人知道怎麼做嘲笑集裝箱。解決()?

+1

您使用的容器是什麼? – Lazarus 2009-11-24 12:49:58

+0

我使用溫莎城堡 – Omu 2009-11-24 12:53:04

回答

0

我做到了,是這樣的:

//code inside the setup method 
var c = new Moq.Mock<IWindsorContainer>(); 
var l = new Moq.Mock<ILookupService>(); 
l.Setup(o => o.GetItems(It.IsAny<String>())).Returns(new List<LookupItem>()); 
c.Setup(o => o.Resolve<ILookupService>()).Returns(l.Object); 
LocatorConfigurator.SetContainer(c.Object); 
+3

我真的試圖避免這種情況,並使用馬克和肯特上面顯示的。 – 2009-11-25 15:47:47

4

問題是,你爲什麼要以這種方式解決它?如果你不是已經依賴注入,那麼你可以很容易地模擬:

public class HomeController 
{ 
    private readonly IOrganisationService organisationService; 

    public HomeController(IOrganisationService organisationService) 
    { 
     this.organisationService = organisationService; 
    } 

    public ActionResult Index() 
    { 
     var x = this.organisationService; 
    } 
} 
+0

不,不是這樣,我只是試圖簡化,我實際上需要它 – Omu 2009-11-24 12:54:00

+0

@歐姆:爲什麼你需要它那樣? – 2009-11-25 15:46:57

6

你不能,因爲有關解決方法是一個靜態方法。這是靜態類型被考慮的很多原因之一邪惡當談到單元測試(因此代碼的一般可組合性)。

您似乎正在應用稱爲服務定位器的(反)模式,並且您目前正在遇到與其相關的許多問題之一。

一個更好的解決辦法是使用構造函數注入這樣的:

public class HomeController 
{ 
    private readonly IOrganisationService organisationService; 

    public HomeController(IOrganisationService organisationService) 
    { 
     if (organisationService == null) 
     { 
      throw new ArgumentNullException("organisationService"); 
     } 

     this.organisationService = organisationService; 
    } 

    public ActionResult Index() 
    { 
     var x = this.organisationService; 
     // return result... 
    } 
} 

現在,您可以讓您選擇的DI容器從外面解決HomeController的實例。這是一個更靈活的解決方案。

+0

爲什麼downvote? – 2009-11-24 14:26:10

0

一些容器(例如Windsor)有一個從接口繼承的容器。如果你使用這個,那麼它是隱式地可嘲弄的。如果你已經創建了一個靜態方法,你可以打開解決方案,那麼如上所述,它不能被嘲笑是不可取的。如果你的容器沒有從接口繼承(或者你正在使用的服務定位器模式),那麼依賴於一個靜態方法,然後改變這個實現,以便它是基於實例的,因此可以嘲弄。

但是,我同意上面的帖子。你不應該真的需要從你的代碼中引用你的容器。這將您的應用程序耦合到一個容器,該容器是您嘗試通過使用容器避免的事情。