Junit 良好实践
我有一个代码可以从数据库中检索很少的信息。 例如,如果您传递人员 ID,方法将返回您的人员详细信息,例如:
姓名: XXX X XXX
地址: XXXXXXXXXXXXX XXXXX
电话: XXXXXX
在 Junit 中测试此类代码的良好做法是什么? Junit 有数据库连接是个好习惯吗?
JUnit 将连接到数据库并检索同一人 ID 的信息并进行断言,这是一个好的做法吗?
谢谢。
I have a code which retrieves few information from Database.
For example if you pass person Id, method will return you person details like:
Name: XXX X XXX
Address: XXXXXXXXXXXXX XXXXX
Phone: XXXXXX
In Junit what is the good practice to test this type of code? Is it good practice that Junit to have DB connection?
Is it a good practice, that JUnit will connect to DB and retrieve information for same person Id and do assertion.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要测试真正需要与数据库配合使用的代码,您应该查看 dbunit。不过,应该尽可能少的代码了解数据库 - 允许您在测试其他组件时伪造“获取或更新数据”部分。
我强烈建议混合使用数据库测试 - 许多针对内存数据库的单元测试(例如 HSQLDB)以及“足够的”集成测试,与将在生产中使用的真实数据库进行对话。您可能很想确保您的所有测试实际上可以在两种环境中运行 - 通常针对 HSQLDB 进行开发,然后针对类似生产的数据库运行(通常设置/拆卸速度较慢) )在签入之前和持续构建中。
For testing the code that really needs to work with the database, you should look at dbunit. As little of the code as possible should know about the database though - allowing you to fake out the "fetch or update the data" parts when testing other components.
I'd strongly advise a mixture of DB tests - lots of unit tests which hit an in-memory database (e.g. HSQLDB) and "enough" integration tests which talk to the real kind of database that will be used in production. You may well want to make sure that all your tests can actually run against both environments - typically develop against HSQLDB, but then run against your production-like database (which is typically slower to set up/tear down) before check-in and in your continuous build.
听起来您正在谈论诸如数据访问对象之类的东西。我想说用真实的数据库测试这类事情是很重要的。查看 H2 以获得非常适合测试的快速内存数据库。创建填充的对象,使用持久性代码将其保存到数据库,然后将其加载回来。然后确保您返回的对象与您最初保存的对象具有相同的状态。
考虑使用 Spring 测试框架来获取帮助 管理持久性测试中的事务以及一般测试支持(如果您在其他地方使用 Spring)。
It sounds like you're talking about something like a Data Access Object. I'd say it's essential to test that kind of thing with a real database. Look at H2 for a fast, in-memory database that's excellent for testing. Create your populated object, use your persistence code to save it to the database and then to load it back. Then make sure the object you get back has the same state as what you saved in the first place.
Consider using the Spring test framework for help managing transactions in persistence tests and for general test support if you're using Spring elsewhere.