开发者

Mocking System.Data.SqlClient.X classes

开发者 https://www.devze.com 2023-03-26 11:52 出处:网络
We have several places in our code-base where we do something similar to the following: DataTable dt = new DataTable();

We have several places in our code-base where we do something similar to the following:

DataTable dt = new DataTable();
using (DatabaseContext context = DatabaseContext.GetContext(false)) {
    IDbCommand cmd = context.CreateCommand("SELECT * FROM X");
    SqlDataAdapter dataAdapter = new SqlDataAdapter((SqlCommand)cmd);
    dataAdapter.Fill(dt);
}
return dt;

How can we use a Mock Testing framework like Moq to remove our testing dependency on the database? I'd like to mock up the DataTable that gets returned.

Clarification: we have plans to change this code but currently can't. Is it possible at all to 开发者_开发问答mock as is?


I would suggest using Repository pattern, which hides all database specific code inside repository. You can mock your repository in order to test your logic in a layer above.

Use a repository to separate the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model. The business logic should be agnostic to the type of data that comprises the data source layer. For example, the data source layer can be a database, a SharePoint list, or a Web service.

The repository mediates between the data source layer and the business layers of the application. It queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source. A repository separates the business logic from the interactions with the underlying data source or Web service.


By can't change code I think You mean You can't do a big refactor. Here's what I suggest.

  1. Extract code You provided to a method.
  2. Make it virtual
  3. If it is not make it protected or public
  4. Inherit from class containing this method and name it OriginalClassNameTesting for example
  5. Override method and return whatever DataTable You wan't
  6. In tests use Your OriginalClassNameTesting class instead of original one.

This pattern is called 'Extract and Override' and it's one of many presented in great book - http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052.

Some may not like that You are adding virtual method just for testing. So what, this is just a first step. You said You have plans for refactoring. Then it will be important to have tests in place so that You are sure You didn't brake anything. And in Java every method is virtual by default (or am I wrong?)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号