问题描述
Devs告诉我这位高级主管,但对Hibernate的经验不足,将一个实体管理器连接到您的单元测试套件中用于设置您的数据库不是合法的做法。 ......但我很怀疑,因为我已经在几个完成这个工作的地方工作过了。请注意,Hibernate已经被用于设置测试H2 db。
我被要求证明它是合法的。我怎样才能做到这一点?这是一个社区标准的做法吗?有谁知道我可以使用的好链接?虽然我自己在寻找这样的东西,但我在这里闻到了一些宗教信仰,所以我可能需要一个真正的杀手或者其中的大部分。
您的高级开发人员指的是正确的白盒测试。
你只想测试 给定的单位。当你开始涉及数据库或某些外部Web服务时,这会变得更加复杂。但是,问题仍然存在:您仍然只想测试单元测试的一段代码;而不是某个数据库。您是否对hibernate或数据库有信心是无关紧要的。你需要模拟数据库事务,EntityManager等。我会沿着EasyMock的方向来看看。真的,它取决于你想要使用什么。如果你是谷歌的模拟junit,你可能会想出一个结果列表,你可以选择适合你的框架。对于你来说,正确的框架有点超出了本次讨论的范围。
一旦你找到你想要使用的东西,这个想法就是你的单元测试,而不是得到一个真正的EntityManager,你有一个模拟对象,你用这样的方式嘲笑:
The reason why you want to mock an object like that, is because you can't rely on any other code that is not within that one Unit to work properly. Despite what you expect, and despite what the documentation says you should expect, if the code is written poorly, or in your case, if the database fails for some reason, then the unit test will fail. You can see how this might be a problem, because your function may execute flawlessly, but it fails because the database failed. This is not how unit testing is supposed to work - that's why its called unit testing...to test only a single unit at a time.
ALWAYS mock complicated Objects or functionality. Leaving things like String#equals(java.lang.Object) is OK. With doing this, you want to find a good middle ground. If you mock too much of your Unit test, then you lose confidence in the Unit test because your unit test is not actually invoking any actual code of yours. If you don't mock enough, then you are not doing unit testing properly, and your unit test is relying on things that have nothing to do with your code (i.e. database failure, third-party code written poorly, etc).
Your senior devs are correct. If you are using the real EntityManager in your Unit tests, then you are not actually doing unit testing at all.
这篇关于是否正在使用测试实体经理进行法定测试练习?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!