2011-03-17 20 views
2

我希望能夠對我的假存儲庫(使用列表) 和我的真實存儲庫(使用數據庫)運行測試以確保兩者我的嘲笑版本按預期工作,我的實際生產存儲庫按預期工作。我認爲最簡單的方法是使用TestCase我可以使用NUnit TestCase測試嘲諷的存儲庫和真實存儲庫

private readonly StandardKernel _kernel = new StandardKernel(); 
    private readonly IPersonRepository fakePersonRepository; 
    private readonly IPersonRepository realPersonRepository; 
    [Inject] 
    public PersonRepositoryTests() 
    { 

     realPersonRepository = _kernel.Get<IPersonRepository>(); 
     _kernel = new StandardKernel(new TestModule()); 
     fakePersonRepository = _kernel.Get<IPersonRepository>(); 
    } 



    [TestCase(fakePersonRepository)] 
    [TestCase(realPersonRepository)] 
    public void CheckRepositoryIsEmptyOnStart(IPersonRepository personRepository) 
    { 
     if (personRepository == null) 
     { 
      throw new NullReferenceException("Person Repostory never Injected : is Null"); 
     } 
     var records = personRepository.GetAllPeople(); 

     Assert.AreEqual(0, records.Count()); 
    } 

但它要求一個常量表達式。

回答

1

屬性是屬性的編譯時裝飾,因此您放入TestCase屬性的任何內容都必須是編譯器可以解析的常量。

你可以嘗試這樣的事情(未經測試):

[TestCase(typeof(FakePersonRespository))] 
[TestCase(typeof(PersonRespository))] 
public void CheckRepositoryIsEmptyOnStart(Type personRepoType) 
{ 
    // do some reflection based Activator.CreateInstance() stuff here 
    // to instantiate the incoming type 
} 

但是,因爲我想,你的兩個不同的實現可能有不同的構造函數參數這變得有點難看。另外,你真的不希望所有那些動態類型實例化代碼混淆測試。

一種可能的解決方案可能是這樣的:

[TestCase("FakePersonRepository")] 
[TestCase("TestPersonRepository")] 
public void CheckRepositoryIsEmptyOnStart(string repoType) 
{ 
    // Write a helper class that accepts a string and returns a properly 
    // instantiated repo instance. 
    var repo = PersonRepoTestFactory.Create(repoType); 

    // your test here 
} 

底線是,測試用例屬性具有采取常量表達式。但是,您可以通過將實例化代碼放入工廠來實現預期的結果。

1

您可能會看到TestCaseSource屬性,雖然這可能會因相同的錯誤而失敗。否則,您可能需要解決兩個單獨的測試,這兩個測試都會調用第三種方法來處理所有常見的測試邏輯。