使用 hibernate 和注释的单元测试服务层,没有 DAO
单元测试/集成测试以下内容的最佳方法是什么:
@Service("fooService")
public class FooService {
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
/*** Get all **/
@Transactional(readOnly = true)
public List<Foo> getAllFoos() {
final Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(Foo.class);
return crit.list();
}
}
我很高兴使用mockito,但不确定如何利用它的实用性。我见过的大多数情况都需要将 dao/mock dao 作为方法参数传入。
显然,我将推断出更复杂的方法。
What is the best way to unit test/integration test the following :
@Service("fooService")
public class FooService {
@Resource(name = "sessionFactory")
private SessionFactory sessionFactory;
/*** Get all **/
@Transactional(readOnly = true)
public List<Foo> getAllFoos() {
final Session session = sessionFactory.getCurrentSession();
final Criteria crit = session.createCriteria(Foo.class);
return crit.list();
}
}
I am happy to using mockito, but was not sure how leverage its usefulness. Most cases I have seen require the dao/mock dao to be passed in as method parameter.
Obviously I will then extrapolate to more complex methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个类是 DAO,从模拟 Session 等中没有太多好处,除非你有很多逻辑 - 如果你这样做,那么最好将其放置在实际的服务类或模型本身上。
考虑一下您要在这里测试什么:这些方法是否从数据库返回它们应该返回的内容。我将对内存数据库运行集成测试。
This class is the DAO and there's not much to be gained from mocking Session etc. unless you have a lot of logic in there - if you do then that might be better placed in an actual service class or on the model itself.
Think about what are you be trying to test here: whether these methods return what they should from the database. I would run integration tests against an in-memory database.
如果您将 @Resource 注释放在方法上,那么设置测试并使用 SessionFactory 的模拟实现来配置服务(如果这是您所要求的)将会容易得多。
If you put the @Resource annotation on a method, it will be much easier to set up a test and configure the service with a mock implementation of a SessionFactory (if that was what you asked for).
我认为您需要决定一些事情:
I think you have a few things to decide: