2012-03-20 44 views
0

我希望對代碼中的特定字典運行單元測試,嘗試獲取我不希望存在於數據庫中的值(在本例中,key = 1 )。如何在未指定字典值的情況下單元測試KeyNotFoundException

我寫了下面的代碼:

Try 
     Dim s As String = myDict(1) 
    Catch ex As KeyNotFoundException 
     Assert.AreEqual("The given key was not present in the dictionary.", ex.Message) 
    Catch ex As Exception 
     Assert.Fail() 
     Throw 
    End Try 

,工作正常,但代碼分析是抱怨「點心S作爲字符串」聲明,它說,旨意絕不能用於任何東西。那麼這是故意的,因爲我打算爲此拋出一個異常和s是無關緊要的。

但是,我似乎無法找到一種方法來消除代碼中的s。簡單地刪除作業:

Try 
     myDict(1) 
    Catch ex As KeyNotFoundException 
     Assert.AreEqual("The given key was not present in the dictionary.", ex.Message) 
    Catch ex As Exception 
     Assert.Fail() 
     Throw 
    End Try 

現在無法編譯。有關如何做到這一點的任何建議?

回答

0

看起來像我可以把一個線,使用S的字典調用之後做到這一點變量:

Try 
     Dim s As String = theDocumentsWithUserNameDictDto.Dict(1) 
     Assert.Fail("Found unexpected value for dictionary key 1: " & s) 
    Catch ex As KeyNotFoundException 
     Assert.AreEqual("The given key was not present in the dictionary.", ex.Message) 
    End Try 

我還是不希望使用的變量(如果測試通過),但是這確實有向用戶提供額外的清晰度的好處,如果這項測試並不能出於某種原因。

1

不幸的是,真的沒有辦法解決這種類型的代碼。調用myDict(1)是一個索引器,它作爲一個語句不合法(在C#中也是非法的)。爲了測試這個,你需要使用這個表達式作爲法律聲明的一部分。做到這一點

一種方式是通過值作爲參數的方法不使用它

Sub Unused(ByVal o As Object) 

End Sub 

... 

Unused(myDict(1)) 
+0

不幸的是,這只是進一步向下游移動警告:我現在變得「RealDataContextTest.Unused(Object)'的參數'o'從不使用」:) – 2012-03-20 16:39:53

+1

@ bobsmith833你使用了什麼工具?編譯器不應該發出這個警告。無論哪種方式,我只是把這個警告標記爲壓制在這個方法上。讓它成爲默認的「我明確不想使用這個」方法 – JaredPar 2012-03-20 16:46:44

+0

這只是標準的代碼分析,但我已將它設置爲「Microsoft All Rules」。正如你所說,這可能是矯枉過正,但有興趣看看是否有一個簡單的方法來消除這種情況。 – 2012-03-20 16:49:01

0

如果您使用NUnit的框架比

,你可以使用下面的代碼

Dim f As Func(Of Integer, String) = Function(i) myDict.Item(i) 
    Dim a As TestDelegate = Function() f(1) 
    Dim ex As KeyNotFoundException = Assert.Throws(Of KeyNotFoundException)(a) 
    Assert.AreEqual("The given key was not present in the dictionary.", ex.Message) 

這是一個類似的解決方案,它是由JaredPar

另一種選擇是讓測試返回建議一個值並使用ExpectedException屬性,因此代碼可能如下所示:

<TestCase(New Object(0 - 1) {}, Result:=Nothing), ExpectedException(GetType(KeyNotFoundException), ExpectedMessage:="The given key was not present in the dictionary."), Test> _ 
Public Function MyTest() As String 
    Return myDict.Item(1) 
End Function 
相關問題