且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数据访问层单元测试的方式

更新时间:2023-02-20 20:51:37

很遗憾,您找不到能将数据库置于已知状态并允许您对数据库运行CustomerRepository以测试CustomerRepository的工具.但是,答案不是开始使用模拟来模拟所有ADO调用.这样,您最终创建的单元测试实际上并没有测试任何逻辑:它只是在测试代码是按照您认为应该编写的方式编写的.

It's unfortunate that you can't find a tool that puts your database into a known state and lets you run your CustomerRepository against the database to test the CustomerRepository. However, the answer is not to start using mocks to mock out all of the ADO calls. By doing that, you end up creating a unit test that doesn't really test any logic: it's just testing that the code is written the way you think it should be written.

比方说,我最终以编写SQL INSERT作为命令在SQL数据库中创建客户.现在,我们要进行更改,以便客户表具有不同的字段(这会破坏INSERT命令),现在我们应该使用存储过程来创建客户.即使使用测试的实现现在已被破坏,使用模拟的测试仍将通过.此外,如果您将实现固定为使用存储过程,则单元测试现在将失败.如果单元测试在应该失败的情况下继续通过,但在修复系统后又失败了,那该怎么办呢?

Let's say that I end up writing a SQL INSERT as my command to create the customer in the SQL database. Now let's say that we're making a change so that the customer table has different fields (that breaks our INSERT command) and that now we should be using a stored procedure to create the customer. The test with mocks would still pass, even though the implementation it's testing is now broken. Additionally, if you fixed the implementation to use stored procedures, your unit tests would now fail. What is the point of a unit test if it continues to pass when it should fail but then would fail when you fixed the system?

请参阅此问题,以获取其他可能的选择.看来,已标记的答案实际上是最终使用IKVM在C#中使用DBUnit.

See this question for some possible alternatives. It looks like the marked answer is to actually just end up using DBUnit in C# using IKVM.

因此,可能还有其他途径可以继续探索,但是模拟ADO调用只会导致脆弱的测试,而实际上并没有测试任何重要的东西.

So, there might be alternative avenues to continue to explore, but mocking the ADO calls is just going to lead to brittle tests that don't really test anything important.