2009-12-03 58 views
0

我有一個單元測試調用一個構造函數,傳遞一個「null」用於測試null的處理。從單元測試調用時意外初始化參數

我期望被調用的方法拋出一個ArgumentNullException,但是當我遍歷代碼時,我看到參數實際上已經被初始化了。

這讓我很難過,儘管我的直覺說它與DI容器(Castle Windsor)有關。

任何人都可以對此有所瞭解嗎?

我的單元測試,空與實例化的委託一起傳遞:

[Test] 
public void ConstructorThrowsAnExceptionWhenImplementationCollectionIsNull() 
{ 
    //assert 
    Assert.Throws<ArgumentException>(() => new CacheImplementationSelector(null, _stubCacheImplementationSelectorDelegate)); 
} 

被調用的方法:

public CacheImplementationSelector(ICollection<ICacheImplementation> implementations, CacheImplementationSelectorDelegate selectorDelegate) 
{ 
    implementations.IsNotNullArgCheck("implementations"); 
    ... 

懸停我的鼠標移到與代碼的實現參數停止在斷點在CacheImplementationSelectorMethod中,visual studio告訴我參數「實現」的計數爲1,[0]爲空。

我使用ReSharper來運行NUnit測試。

爲了完整是TestFixtureSetup和設置如下:

[TestFixtureSetUp] 
public void FixtureSetUp() 
{   
    _mocks = new MockRepository(); 
} 

[SetUp] 
public void Setup() 
{ 
    _listOfImplementations = new List<ICacheImplementation>() { _stubICacheImplementation };    
    _stubCacheImplementationSelectorDelegate = MockRepository.GenerateStub<CacheImplementationSelectorDelegate>(); 
    _stubICacheImplementation = MockRepository.GenerateStub<ICacheImplementation>(); 
    _stubKeyCreator = MockRepository.GenerateStub<ICacheKeyCreator>(); 
    _stubStrategy = MockRepository.GenerateStub<ICachingStrategy>(); 
    _stubEncoder = MockRepository.GenerateStub<ICacheItemEncoder>(); 
    _c = new CacheImplementationSelector(_listOfImplementations, _stubCacheImplementationSelectorDelegate); 
    _testObject = new object(); 
    _yesterday = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0)); 
    _tomorrow = DateTime.Now.Add(new TimeSpan(1, 0, 0, 0)); 
    _testString = "test"; 
    _tooLongKey = "a".Repeat(Cache.MaxKeyLength+1); 
    _tooLongFriendlyName = "a".Repeat(Cache.MaxFriendlyNameLength + 1); 
} 
+0

問題與您的測試或與您的實際應用程序?我在這些測試中沒有看到溫莎...... – 2009-12-04 03:06:50

+1

爲什麼在單元測試中使用容器?容器將編排整個應用程序。單元測試是單獨測試單元... – 2009-12-04 08:07:21

+0

如上所述,這聽起來不可能。必須有某種我們錯過的背景。你能描述併發布簡單的代碼來重現行爲嗎? – 2009-12-04 16:09:27

回答

1

是否有可能,當你通過你看到這條線的[設置]方法執行代碼加強?

_c = new CacheImplementationSelector(_listOfImplementations, _stubCacheImplementationSelectorDelegate); 

該代碼將在您的單元測試之前運行,並且「實施」方法不會爲空。

至於單元測試失敗,我們可以看到IsNotNullArgCheck方法的實現嗎?我認爲這是一些使用反射的擴展方法。那裏可能有bug?

+0

當對單元測試持懷疑態度時,我問了這個問題。所提供的代碼不足以給出完整的答案。無法證實這個答案是解決方案,但很可能,因此被接受。 – Ben 2010-01-10 00:13:30

相關問題