通过模拟数据层或使用嵌入式数据库进行单元测试 [英] Unit testing by mocking the data layer or using embedded database

查看:112
本文介绍了通过模拟数据层或使用嵌入式数据库进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于单元测试,是更好地模拟数据层还是使用像derby这样的嵌入式数据库?

For unit testing is it better to mock the data layer or use an embedded database like derby?

我知道这也取决于测试的目的。但是,如果我选择了德比,则不必模拟所有对象,并且我认为这样做会更容易。另一方面,我知道这更多地用于集成测试。

I know that it also depends on the purpose of the testing. But if I go with derby I don't have to mock all the objects and I assume that would be easier. On the other hand I understand that that is more towards integration testing. So which one is more common for unit testing?

谢谢。

根据评论更新:

所以我现在配置了德比,但是我的经理坚持使用easymock。我们正在使用jpa,我们有大约20个表=>数据模型。那么对于像项目模型这样的每个方法,我都应该为其所有方法指定mockedProject的返回类型吗?像getProjectName(),getProjectId()等一样?我还应该模拟持久性管理器对象。与配置像derby这样的嵌入式db相比,我认为这很多。

So I have derby configured now but my manager insists on using easymock. We are using jpa and we have about 20 tables => data models. So then for each method like for project model should I specify the return type of the mockedProject for all its methods? Like getProjectName(), getProjectId(), etc? And also should I mock the persistent manager object. I thought that is just a lot in comparison with just configuring an embeded db like derby.

推荐答案

如果您使用的是JPA,则无需模拟您的Project对象,因为它们可能只是愚蠢的POJO的对象, 对?您只需要模拟持久性管理器对象(EntityManager)。在最简单的情况下(如果您将Mockito或Easymock与 niceMock一起使用),您可能只需要创建模拟并注入它就可以了。根据您要测试的内容,您可能会想做更多的事情:验证保存合并方法被调用,指定它是通过 get 调用等返回特定的Project对象。

If you're using JPA, you don't need to mock your Project objects, because they are probably just dumb POJO's, right? What you need to mock is just the persistence manager object (EntityManager). In the simplest case (if you're using Mockito or Easymock with 'niceMock') you may just need to create the mock and inject it and that's it. Depending on what you're testing, you will probably want to do more than that: verifying that a save or merge method is called, specifying that it is to return a particular Project object on a get call, etc.

模拟EntityManager有几个好处:

Mocking the EntityManager has several benefits:


  1. 它运行非常快-甚至比嵌入式数据库还要快。这些测试将运行很多次,因此,不要让它们负担太重。

  2. 您不需要填充真实的数据库。尽管您可能需要针对某些集成测试执行此操作,但是很难提供一个涵盖所有所需方案的数据库。通过模拟,您可以在测试本身中创建所需的特定方案。

  3. 您可能希望测试在现实中很难实现的某些条件,例如IO错误。或数据库中已经存在但违反某些约束的数据。使用模拟,您只需告诉模拟在调用方法时抛出异常。连接到真实的数据库(甚至是嵌入式数据库)将很难(如果不是不可能的话)实现它。

模拟POJO没有这些好处。执行POJO的代码与模拟POJO一样快。填充POJO可能会有些麻烦,但不如设置模拟的POJO的行为那么麻烦。而且,由于POJO(通常)没有太多的外部依赖方式,因此很少需要第三个好处。

Mocking a POJO has none of these benefits. It's just as fast to execute the code of a POJO as a mocked POJO. Populating a POJO can be a bit of a pain, but not as much as setting up the behavior of a mocked POJO. And since POJO's don't (normally) have much in the way of external dependencies, the third benefit is rarely required.

这篇关于通过模拟数据层或使用嵌入式数据库进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆