Method for unit testing an extension method for SqlCommand
I've created an extension method for SqlCommand that allows some additional work before executing the command:
public static SqlDataReader ExecuteMyReader( this SqlCommand sqlCommand )
{
// Some calculations here
return sqlCommand.ExecuteReader();
}
My question is what is the best way to unit test this extension method?
Should 开发者_开发知识库I test it directly against a database?
Or should I try and create a mock object? If this is the case I've tried doing this through Moq but as SqlCommand is a sealed class I can't seem to mock it.
Can you pull the calculations out to their own method and test them separately? As you've discovered, it's difficult and unrewarding to write unit tests for functions at this level of granularity.
If you wish to test that the command actually does update the database, you'd be writing an integration test. The best method of testing this would then be:
- Set up a simple database
- Execute the test
- Rollback the database.
- Repeat
This is fine, because that's what you care about. If this was to be mocked (there is no point), what would you be testing? How do you know it works?
The only time you'd wish to mock this is for code which consumes your extension method. But as you wish to test an extension method, there is only one way, and that is to actually hit the database.
You are right to say you cannot test the method as a whole.
I don't know the nature of your calculations but if they can be split out into another function, that function could be unit tested. This would be useful to insure that the calculation, which I assume is the meat of your implementation, works correctly.
精彩评论