2013-11-23 37 views
3

我想重構項目中的一些類,使它們可以使用接口和依賴注入進行測試。但我與以下幾點:c#依賴注入接口和隱藏內部

public interface IInterfaceA 
{ 
    void SomePublicMethod(); 
} 

public class ConcreteObject : IInterfaceA 
{ 
    public void SomePublicMethod() { ... } 
    public void SomeOhterMethod() { ... } 
    public void YetAnotherMethod() { ... } 
} 

public class AnotherConcreteObject 
{ 
    private IInterfaceA _myDependency; 
    public AnotherConcreteObject(IInterfaceA myDependency) 
    { 
     _myDependency=myDependency; 
    } 
} 

到目前爲止一切都很好,很標準的代碼。 AnotherConcreteObject需要調用SomeOtherMethod,但我不希望其他類(例如不同的程序集)能夠調用SomeOtherMethod。所以外部SomePublicMethod應該是可見的,但SomeOtherMethod不應該是。只有AnotherConcreteObject的實例應該能夠調用SomeOtherMethod。 SomeOtherMethod將例如設置一個內部屬性,稍後由YetAnotherMethod使用來確定應該發生什麼。在所有其他情況下,內部屬性被設置爲默認值,例如當另一個方法從AnotherConcretObject之外的任何其他類中調用時。

當不使用接口時,這是可能的,因爲AnotherConcreteObject與ConcreteObject在同一個程序集中,所以它可以訪問內部屬性和方法。不同程序集中的類不能設置此屬性或調用方法,因爲它們無法訪問內部屬性和方法。

+0

如果'AnotherConcreteObject'需要調用不在公共接口中的東西,那麼它應該依賴於'ConcreteObject'而不是接口 - 或者可能另一個暴露'SomeOtherMethod'的接口。 –

+0

但是如果AnotherConcreteObject直接依賴於Concrete對象,這是不是使AnotherConcreteObject更難測試(或不可能)?我希望AnotherConcreteObject可以使用嘲諷進行測試 – rekna

+0

由於AnotherConcreteObject調用的實例SomeOtherMethod設置了內部屬性,您是否遇到了測試AnotherConcreteObject的問題? – Spock

回答

1

有幾個可能的解決方案,這依賴於你在做什麼:

1如果SomePublicMethod是公開的,但SomeOtherMethod是內部的,那就不要把它們放在同一個班級,他們可能做的很不同的事情,所以關注的分離原則發揮作用。 2如果ConcreteObject沒有狀態並且不會產生副作用,或者如果您不打算對它並行運行測試,即具有單位行爲,那麼它可能不需要模擬,因此可以直接訪問它。

+0

SomeOtherMethod和SomePublicMethod應該在同一個類中,因爲SometOtherMethod會影響其他部分中類的行爲。 – rekna

+0

@rekna如果兩個方法必須在同一個類中,那麼我會問爲什麼一個是內部的,另一個是公共的。這可能表明班級做得太多了。 –

+0

假設兩種方法配置/設置類,而第三種方法則執行類的主要功能。這些方法會影響此主要功能的控制流。 – rekna