Search code examples
c#.netunit-testingfluent-assertions

Checking ShouldThrow Exception.Data in Fluent Assertions in .NET


OK, I am running a unit test to see if the Exception.Data property contains a specific value against a specific named key.

Exception.Data is of type IDictionary. IDictionary only has 2 overloads which I cant see a way to verify what is in the dictionary.

I have the following code that throws the exception:

public class MyClass
{
    public void ThrowMyException()
    {
        throw new MyException();
    }
}

public class MyException : Exception
{
    public MyException()
    {
        this.Data.Add("MyKey1", 212);
        this.Data.Add("MyKey2", 2121);
    }
}

Then a test to try and verify that MyKey1 = 212 and MyKey2 = 2121:

[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        MyClass classUnderTest = new MyClass();

        Action test = () =>
        {
            classUnderTest.ThrowMyException();
        };


        test.ShouldThrow<MyException>() //.And.Data.Keys.Should().Contain("")

    }
}

I want to test that the Data Contains MyKey1 with a value of 212 and MyKey2 with a value of 2121.


Solution

  • If you want to test if a key-value pair exists in a non-generic IDictionary, you need to create a DictionaryEntry object and check if it exists in the dictionary.

    So in your case it would be something like this:

    test.Should.Throw<MyException>().And
        .Data.Should().Contain(new DictionaryEntry("MyKey2", 2121));