I still think sealed is bad. Today, I was working on some code that needed to handle SqlExceptions depending on the error number it contained. Naturally, I wanted to write a test for it. So, I wrote the test, and got so far as to try to create an instance of SqlException.
Oops. Not only is SqlException sealed, it’s constructor is internal, to make sure you don’t create any Exceptions yourself.
I know I should not throw SqlExceptions. Instead, I should catch SqlExceptions in my data access layer, and possibly rethrow exceptions using my own exception-class. But that would require a big change instead of a small one, and totally break go against the rest of the code base.
I want to create an instance of SqlException and throw it, damn it. Who are you to tell me what I want and don’t want? Instead, I had to write code to create the exception through reflection, which is an unnecessary pain for me.
Somebody out there might run into the same problem, so here is a class that does it for you. It’s for .NET1.1, since this is what I work on. It won’t work on .NET2, sorry.
Mocking SQLException…
I’m working on a presentation about Testing, and one of the technics I would like to show is MockObjects….
Left by Just Coding on November 26th, 2006
I created an adaptation of your code for .NET 2.0. It’s at http://blogs.chayachronicles.com/sonofnun/archive/2006/12/01/89.aspx
Thanks for your publishing the majority of it!
Left by Mike on December 2nd, 2006
I found another instance of a SQLExceptionCreator for .NET 2.0 at
http://blogs.msdn.com/rido/archive/2006/11/26/mocking-sqlexception.aspx
Left by Justin Kohnen on August 20th, 2009