2014-01-07 29 views
0

我正在學習MVP,測試驅動方法和工廠模式。我想寫幾個簡單的類來維護一個人的數據和存儲庫。這個人的數據將被存儲在sql中並用xml進行測試。我閱讀了關於StructureMap的內容,但不想使用它,而是想使用一個簡單的工廠實現,最終也可以幫助我連接單元測試用例。這裏是我的課程:理解MVP模式的測試驅動方法?

class Person 
{ 
    int id; 
    string name; 
} 

interface IPersonRepository 
{ 
    Person GetPerson(int id) 
    { 
    } 
} 

class PersonRepositorySql : IPersonRepository 
{ 
    Person GetPerson(int id) 
    { 
     //Fetch from sql 
    } 
} 

class PersonRepositoryXML : IPersonRepository 
{ 
    Person GetPerson(int id) 
    { 
     //Fetch from XML 
    } 
} 

static class PersonRepositoryFactory 
{ 
    static PersonRepositorySql Create() 
    { 
     return new PersonRepositorySql(); 
    } 

    static PersonRepositoryXML CreateTest() 
    { 
     return new PersonRepositoryXML(); 
    } 
} 

class Presenter 
{ 
    Presenter(View _view) 
    { 
    } 

    void DoSomething() 
    { 
     IPersonRepository fact = PersonRepositoryFactory.Create(); 
     //fact.GetPerson(2); 
    } 

} 

class PresenterTest 
{ 
    void Test1() 
    { 
     IPersonRepository fact1 = PersonRepositoryFactory.CreateTest(); 
     //fact1.GetPerson(2); 
    } 
} 

請告訴我,如果我採取的方法是正確的和任何其他建議。另外,因爲我沒有在構造函數中傳遞對象,所以這不作爲依賴注入的例子嗎?

+0

沒有什麼是基於注入的抽象。這是測試和TDD的核心組件。我認爲你應該重新閱讀你的參考資料,特別是關於緊耦合和具體實現的部分..以及依賴注入。 –

+0

請檢查... – user2645830

回答

1

所有首先不要取決於類,如果你希望你的代碼的可測試性,取決於接口由類實現。

依賴於您的工廠的類應該預計它由他們的用戶注入。由於這個原因,您可以輕鬆地在測試項目中交換存儲庫,而不必更改測試代碼。

因此任何工廠必須要改變的東西是這樣的:

class PersonRepositoryXML: IPersonRepository 
{ 
    public IPerson GetPerson(int id) 
    { 
     //Fetch from XML 
    } 
} 

public interface IPersonRepository 
{ 
    IPerson GetPerson(int id); 
} 

// a dependent class 
class SomeDependentClass { 
    public SomeDependentClass(IPersonRepository repository) { 
     this.repository = repository; 
    } 

    public void Foo() { 
     var person = repository.GetPerson(10); 
     // do smth to the person :) 
    } 
} 

我會推薦閱讀this書有關依賴性注入的設計模式的進一步細節。

+0

謝謝。根據您的建議編輯我的答案。我爲PersonRepository添加了一個接口,但是我還應該爲PersonRepositoryFactory添加一個接口嗎?當我已經可以切換到XML或SQl存儲庫時,它會提供什麼好處... – user2645830

+0

我不會親自使用工廠。我會使用依賴容器將事物綁定在一起。如果你不想使用DI庫,我仍然會將庫封裝到接口中,以便測試與該工廠有關的事情。 – SOReader