[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 511
  • Last Modified:

Override class method in unit test to return expected results

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.

1 Solution
Jesse HouwingScrum Trainer | Microsoft MVP | ALM Ranger | ConsultantCommented:
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

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now