views:

130

answers:

3

Hi,

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.

Thanks

+1  A: 

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.

Finglas
Isn't there a step missing in your test? The part where you see that the database is in the state you want after the test has been executed?
That would be included as part two, the execution of this test. In other words, Arrange, Act and Assert.
Finglas
+1  A: 

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.

David Seiler
This is a good option too.
Finglas
I can pull the calculation out so it is in its own method however I would rather this method be kept private is there a way of testing a private method?
Simon G
@Simon - See http://stackoverflow.com/questions/51950/how-do-i-allow-assembly-unit-testing-one-to-access-internal-properties-of-anoth
Finglas
A: 

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.

Tom Cabanski