Override class method in unit test to return expected results

Posted on 2011-10-26
Last Modified: 2013-12-16
In a unit test, I would like to be able to change the default behaviour of a method for a class instance in order to validate that my class handles the edge case properly.

For example,

In my test case when I make a call as follows

System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection ();

For this particular test case I want it to always return an Exception with particular details.

This way I can always ensure that the code for database connection failures work.

Any thoughts on how I might solve this problem.

Question by:craftedsoftware
    1 Comment
    LVL 17

    Accepted Solution

    You have two options here:

    1) Use a mockign framework such as Microsoft Moles or TypeMock Isolator to replace your SqlConnection object while the test is running
    2) Refactor your code to receive a SqlConnection object or have a virtual method that creates the SqlCOnnection. You can then either "inject" the connection into your code under test (and supply it with your own inherited version which always throws exceptions) or override the creation method to create an inherited connection which always throws exceptions.

    In order to make this easier, you can use IConnection instead of SqlConnection.

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Join & Write a Comment

    This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
    Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
    It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
    Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

    745 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    16 Experts available now in Live!

    Get 1:1 Help Now