Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 671
Andez Avatar asked Jan 19 '16 14:01

Andez


2 Answers

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));
like image 101
Domysee Avatar answered Sep 20 '22 17:09

Domysee


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");

    }
}
like image 24
Ben Avatar answered Sep 22 '22 17:09

Ben