使用 NHibernate 编写单元测试的最佳实践
我是 NHibernate (+Fluent) 的新手,在构建我的代码以使其可测试时,我无法决定什么是最佳策略。我有一个简单的结构,包括域模型、将模型映射到数据库的映射,以及一些具有行为的类,这些行为将针对模型类并执行事务以更新和从数据库中读取数据。除此之外我还有更多内容,但这与这里无关。
现在,当谈到单元测试时,对我来说很自然的是向行为类注入一些东西,这样它们就可以获得一个用于测试的 SQLite 数据库,或者无论配置如何的真实数据库。这有道理吗?我无法决定的是注入什么。
- 我可以注入 ISession,但我想我想为每个 - 嗯 - 会话使用新会话?如果是这样,我需要外部的东西来创建会话,这可能会解决问题?
- 我可以注入SessionSource吗?在这种情况下,行为类可以使用它自己创建会话。但是,我看到 SessionSource 用于 BuildSchema - 我认为我只想做一次?
- 我看到的第三个选项 - 以及我到目前为止所做的 - 是创建一个 SessionFactory 来为我创建一个会话。使用它,我可以添加一个 using 子句,并在函数完成时处理会话。我有一个 SessionFactory 接口以及一个常规和单元测试实现。注入常规或单元测试实现,我得到正确数据库的会话。
我走在正确的轨道上吗?我应该如何构建我的代码以使用 NHibernate 为代码编写单元测试?我应该注意哪些最佳实践?
I'm new to NHibernate (+Fluent), and I can't decide on what's the best strategy when it comes to structuring my code to make it testable. I have a plain structure including a domain model, mappings to map the model to database, and a few classes with behavior which will work towards the model classes and do transactions for updating and reading out data from the database. I have more on top of this, but that's not relevant here.
Now, when it comes to the unit testing what seems natural to me is to inject something to the behavior classes such that they will get a SQLite database for testing, or the real database however this is configured. Does this make sense? What I can't decide is what to inject.
- I could inject the ISession, but I assume I'd want to use new sessions for each - well - session? If so I'd need something outside to create the sessions, which might just move the problem?
- Could I inject the SessionSource? In this case the behavior classes could create sessions themselves using this. However, I see the SessionSource is used to BuildSchema - something I assume I only want to do once?
- The third option I see - and what I've done this far - is to create a SessionFactory which creates a session for me. Using this I can add a using-clause and have the session disposed when the function finishes. I have a SessionFactory-interface and a regular and a unittest implementation. Injecting either the regular or unittest implementation I get a session for the right database.
Am I on the right track? How should I strcuture my code for writing unit tests for code using NHibernate? Any best practices I should be aware of?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想查看 Ayende 的这篇博客文章:
Nhibernate 单元测试。他有一个测试基类,用于使用内存数据库(sql lite)配置会话。这似乎与您的第三个选项类似。
You may want to check out this blog post by Ayende:
Nhibernate Unit Testing. He has a test base class that configures the session with an in memory database (sql lite). This seems be similar to your third option.