关于模拟框架

时间:2016-02-12 04:16:40

标签: java unit-testing mocking powermockito

我正在使用powermock,我有几个问题。

  1. 我们是否需要修改我们的代码,以防我们发现(在后期阶段)它无法使用powermockmockito或任何其他测试框架进行测试? 即,我们是否应该停止编写静态/私有方法,某些框架无法对其进行测试(我知道powermock具有测试这些方法的能力)

  2. 在模拟/监视对象时应该调用实际方法吗?即,如果执行进入调试点,我通过在方法调用中保留调试点来检查它吗?

  3. 请帮助我理解这些事情。

2 个答案:

答案 0 :(得分:0)

1。)不可测试/可测试性差的代码主要是设计不佳的标志,所以是的,您应该更改代码。大规模静态方法/状态是代码气味,这意味着设计不良并最终导致更高的维护工作。 私人方法通常应在其公共呼叫者中进行测试,因为他们只是帮助者。在我看来,永远不应该直接测试私有方法,因为它们可能随时通过重构进行更改,因为类的公共接口应该是某种稳定的。

2。)模拟时,不应调用目标方法/对象。间谍应该调用spied方法/对象

答案 1 :(得分:0)

I was brought into a team that had a giant legacy system, but they were adding new class/methods to it. These classes and methods would touch up to 10 DAO/DAL. However, these DAO/DAL had been up and running for 20+ years and had very few failures. So their behavior was pretty much expected. Using mocks in this case worked out really well, I could write purely unit tests for the new code, and mock all the DAOs to return objects/ or exceptions to check our boundary scenarios.

Mocks are great for when you have to access Data bases, make connections over the internet, or have a particularly large class you don't want to instantiate to only call one method from. If you have a class that requires many objects in its constructor(which would each need to be instantiated), but really you just need to get Class.CanRetry() (which would either return true or false), a mock would work lovely in this instance.

A hammer is a great tool, but it won't help you unclog a toilet... at least well. Mocks are a great tool to know how to use, but there is a time and place for them.

Please refer to these two great articles for more information on how/when to use mocks:

When to Mock

Mocks aren't stubs (bit of a longer read, but great information)

In regards to your second question this next article will give you the best understanding of the difference between all the different types of "test doubles" which includes mock objects, Test spys, dummy objects, etc... Agile Engineering: Test Doubles

相关问题