java 如何对 SQL 查询进行单元测试?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4265884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to unit test an SQL query?
提问by Amir Rachum
I have a class DBHandler
which takes a query, runs it through the SQL server, checks for errors and returns the result. How can I unit test this class?
我有一个类DBHandler
,它接受一个查询,通过 SQL 服务器运行它,检查错误并返回结果。我如何对这个类进行单元测试?
Edit: I'll try to be more precise:
DBHandler
is in charge of passing the query to the server. In order to test that it actually does that, throws the correct exceptions, etc., I want to connect it to a mock DB which I will populate. My question is - how to do that? How can I create a mock "server" that handles calls?
编辑:我会尝试更精确:
DBHandler
负责将查询传递给服务器。为了测试它是否真的这样做了,抛出了正确的异常等,我想将它连接到我将填充的模拟数据库。我的问题是 - 如何做到这一点?如何创建处理呼叫的模拟“服务器”?
采纳答案by Adeel Ansari
回答by Hymanson Pope
I'd use dependency injection to pass in the database connection or something similar, so that the whole thing can be mocked out in the tests. Then you can write tests where the mock query throws exceptions, returns various errors or valid results. Then your tests are just checking that DBHandler
performs correctly.
我会使用依赖注入来传递数据库连接或类似的东西,这样整个事情就可以在测试中模拟出来。然后,您可以编写模拟查询抛出异常、返回各种错误或有效结果的测试。那么您的测试只是检查DBHandler
是否正确执行。
回答by fredt
A quick solution for a mock db works like this:
模拟数据库的快速解决方案如下所示:
Setup an HSQLDB test server independent from your app.
Populate with test data.
Use conditional code where you connect to your real database, to connect to the test server. A property in your application can control this.
Test the application
设置独立于您的应用程序的 HSQLDB 测试服务器。
用测试数据填充。
使用连接到真实数据库的条件代码连接到测试服务器。应用程序中的属性可以控制这一点。
测试应用程序
回答by duffymo
You'll want to either use an in-memory test database that you create and populate on set-up or make all your tests transactional so they don't alter your test database.
您将想要使用在设置时创建和填充的内存中测试数据库,或者使所有测试都具有事务性,这样它们就不会改变您的测试数据库。
You'll have to worry about the presence of data.
您将不得不担心数据的存在。
If you're using Spring, they have support for transactional unit tests.
如果您使用的是 Spring,则它们支持事务性单元测试。
It's not clear what you're asking. You already know about JUnit. What do you think you're missing?
不清楚你在问什么。您已经了解 JUnit。你觉得你缺少什么?