简体   繁体   中英

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM