简体   繁体   English

单元测试SqlCommand扩展方法的方法

[英]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: 我为SqlCommand创建了一个扩展方法,在执行命令之前允许一些额外的工作:

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. 如果是这种情况我尝试通过Moq这样做,但由于SqlCommand是一个密封的类我似乎无法模仿它。

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. 这将有助于确保我假设的计算是您的实现的核心,正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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