vb.netunit-testingdictionarykeynotfoundexception

How to unit test KeyNotFoundException without assigning dictionary value


I wish to run a unit test on a particular dictionary in my code, trying to get a value I don't expect to be in the database (in this case, key=1).

I have written the following code:

    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

which works fine, but the code analysis is complaining about the "Dim s as String" declaration, as it says that s will never be used for anything. Well that's intentional, because I intend for this to throw an exception and s is irrelevant.

However, I can't seem to find a way to eliminate s from the code. Simply removing the assignment:

    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

now fails to compile. Any suggestions on how to do this?


Solution

  • Looks like I can do this by putting a line after the dictionary call which uses the s variable:

        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
    

    I still don't expect the variable to be used (if the test passes), but this does have the benefit of providing extra clarity to the user if the test does fail for some reason.