简体   繁体   English

如何单元测试数据库类

[英]How to unit test Database Class

This has probably been asked many times but here it goes : 这可能已被多次询问,但在这里:

I have a class full of db connections 我有一个充满数据库连接的类

open connection 打开连接
query db 查询数据库
read values 读取值
close connection 密切联系

How should I unit test this stuff? 我该如何对这些东西进行单元测试?

Do I need to create a fake database? 我需要创建一个假数据库吗? I guess I could mock the MySql classes (for c#), but that's also a lot of work. 我想我可以模拟MySql类(对于c#),但这也是很多工作。

Some of the statements are "INSERT INTO", what should I do about this? 有些陈述是“INSERT INTO”,我该怎么办呢?

Stuff that are hard to test is often tightly coupled or not following the Single Responsibility principle . 难以测试的东西通常紧密耦合或不遵循单一责任原则

First of all. 首先。 Split your datalayer. 拆分数据层。 Look at the repository pattern . 查看存储库模式 Each entity (table or view) should have it's own class fetching data. 每个实体(表或视图)都应该拥有自己的类获取数据。

Use data interfaces instead of specific driver implementation: IDbConnection instead of SqlConnection . 使用数据接口而不是特定的驱动程序实现: IDbConnection而不是SqlConnection Use DbProviderFactory to get the proper connection implementation. 使用DbProviderFactory来获得正确的连接实现。 Then use connection.CreateCommand() to get a command etc. 然后使用connection.CreateCommand()来获取命令等。

Doing all that would make it a whole lot easier to test your data layer. 尽一切努力使测试数据层变得更加容易。 And remember, the datalyer should not have any logic. 请记住,数据库不应该有任何逻辑。 It's only purpose is to load data from a data source. 它的唯一目的是从数据源加载数据。

But if you don't want to change stuff: Working against a database is the easiest way. 但是如果你不想改变东西:对数据库工作是最简单的方法。 Remove all data and insert new test data before each test (to remove any changes during a previous test). 删除所有数据并在每次测试之前插入新的测试数据(以删除上一次测试期间的任何更改)。

Easiest would be to create a new test db and make some insert querys and then store the result sets in a list or something and then just run it with the debugger to see if it's stores the resultset in the list you've created. 最简单的方法是创建一个新的测试数据库并制作一些插入查询,然后将结果集存储在列表或其他内容中,然后使用调试器运行它,看它是否将结果集存储在您创建的列表中。

Don t have any intsert into in the source code, use sql management studios and make the inserts there instead until you know that the connections and everything works. 不要在源代码中插入任何intsert,使用sql管理工作室并在那里插入,直到你知道连接和一切正常。 Just tab out all those values for now. 现在就删除所有这些值。

You can use a live MySql database running locally on your machine. 您可以使用在您的计算机上本地运行的实时MySql数据库。

I have made a Nuget package for this purpose, that you can add to your project: https://github.com/stumpdk/MySql.Server 我为此目的制作了一个Nuget包,你可以添加到你的项目中: https//github.com/stumpdk/MySql.Server

It starts a local MySql server every time you run your tests. 每次运行测试时它都会启动一个本地MySql服务器。 It's quick, gives a solution your team can share, and you don't have to spent your time installing a server. 它很快,提供了团队可以共享的解决方案,而且您不必花时间安装服务器。

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

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