7

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.

Andez
  • 5,588
  • 20
  • 75
  • 116
  • What do you mean you cannot see any extension methods? `test.ShouldThrow().And.Data.Keys.Should().Contain("")` seems fine to me – Domysee Jan 19 '16 at 14:56
  • Sorry, I meant on IDictionary compared to strong typed Dictionary https://github.com/dennisdoomen/fluentassertions/wiki/Documentation-(Release-2.2)#dictionaries There is 2 overload methods on Data.Should().Contain – Andez Jan 19 '16 at 14:58

2 Answers2

10

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));
InteXX
  • 6,135
  • 6
  • 43
  • 80
Domysee
  • 12,718
  • 10
  • 53
  • 84
  • Thanks. I was trying with KeyValuePairs then just checked the internals on the Data and noticed it was DictionaryEntry. Still I was trying to cast this to a Dictionary to no avail, but this works. – Andez Jan 19 '16 at 15:16
1

Basically you should get a reference to your exception and do whatever you need with that. You can cast it and validate the object. Something like this:

[TestClass]
public class UnitTest1
{
   [TestMethod]
    public void TestMethod1()
    {
        MyClass classUnderTest = new MyClass();
        Exception ex;
        try
        {
            Action test = () =>
            {
                classUnderTest.ThrowMyException();
            };
        }
        catch (Exception exception)
        {
            ex = exception;
        }


        test.Should.Throw<MyException>();
        ex.ShouldBeOfType<MyException();
        ((MyException)ex).Data.ShouldContain("MyKey");

    }
}
InteXX
  • 6,135
  • 6
  • 43
  • 80
Ben
  • 538
  • 1
  • 9
  • 24