对依赖于数据库的 Window 服务进行单元测试
我们在.NET 3.5\C# 和 WCF 中有一组服务。 NUnit 测试需要运行服务并侦听请求。 这些服务需要更新的 SQL 数据库才能准备连接。
目前单元测试的 [SetUp] 部分执行两项任务:
- 执行最新的 SQL 脚本来构建数据库。
- 利用一个 System.Diagnostics.Process.Start 以命令行模式运行服务。
它通常可以工作,但服务对某些架构更改很敏感,这有时会导致服务失败。我正在寻找设置数据库和服务的最佳实践,并确保服务最终关闭。
该进程由 MSBuild 运行。
We have a set of services in .NET 3.5\C# and WCF.
The NUnit tests need the services to be running and listening for requests.
The services need an updated SQL database to be ready for connection.
Currently the [SetUp] section of the unit test does two tasks:
- Execute the latest SQL scripts to build the database.
- Utilize a
System.Diagnostics.Process.Start to run the commandline mode of the services.
It usually works but the services are sensitive for certain schema changes, which sometimes fails them. I'm looking for the best practice for setup the database and then the services, and also making sure the services are down at the end.
The process is run by MSBuild.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您正在启动服务,并启动实际执行的服务……变化就是您不再只是进行单元测试。您现在正在进行集成测试。
您确实应该考虑将数据访问抽象为接口。然后,您可以编写该接口的具体实现以进行正常操作,并使用依赖项注入为单元测试注入模拟实现。
If you're starting the services, and hitting actual executing services...changes are you're not just Unit testing anymore. You're now integration testing.
You should really think about abstracting your Data Access into an Interface. You can then code a concrete implementation of that Interface for normal operation and use Dependency Injection to inject a mock implementation for your Unit tests.
单元测试的最佳实践是使用模拟数据库行为而不是真实数据库的模拟对象。
The best practice for unit testing is using mock objects which emulate database behavior instead of the real database.
您对依赖注入 (DI) 做过很多工作吗?
我强烈推荐阅读 Jerry Millers 博客,他有很多关于单元测试和 DI 使用的精彩内容。网。
这是一篇文章,帮助您开始了解依赖注入模式。
阅读完本文后,请查看他在 业务逻辑单元测试。
使用 MSBuild 是一个良好的开始,因此现在需要重构外部服务,然后在测试期间模拟它们。你想要嘲笑有多复杂取决于你。
这里有一篇关于模拟框架的帖子来帮助您入门。
我建议将您的测试分成两个单独的部分:
在测试结束时,您可以使用某种方法停止您的服务使用 [TestFixtureTearDown] 属性。
Have you done much with Dependency Injection (DI)?
I highly recommend reading Jerry Millers blog, he's got lots of great stuff on Unit Testing and DI using .Net.
Here's a post to get your started on The Dependency Injection Pattern.
Once you've read this, have a look at his post on Unit Testing Business Logic.
Using MSBuild is a good start, so now its a case of re factoring out the external services and then mocking them during your test. How complicated you want the mocking to be is up to you.
Here's a SO post on Mocking Frameworks to get you started.
I'd suggest breaking your testing into two separate parts:
At the end of the tests you could stop your services using a method with the [TestFixtureTearDown] attribute.