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.
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));
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");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With