This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a question in the Mockito. Is there any way to mock the static utility classes in the Mockito?
For example, if i need to Mock a factory method, what is the correct way to mock and is the PowerMock best here?
bs vinay wrote:I have a question in the Mockito. Is there any way to mock the static utility classes in the Mockito?
No, Mockito does not allow you to do that. In short, mocking of static classes is considered to be signal of a bad (ok, suboptimal) design of your production code, and one should strive for something more loosely coupled (e.g. via Dependency Injection) which is easier to test. So, this is a design decision by Mockito author(s) and probably won't change.
bs vinay wrote:For example, if i need to Mock a factory method, what is the correct way to mock and is the PowerMock best here?
If what you really want it to mock a static method then PowerMock is a good solution. However, some would argue, that by doing so you are really ignoring an important information that Mockito gives you: namely, that your class is very tightly coupled to some other class. There is a popular saying that "if you can't write test, it means you have bad code". So, yes, you can use PowerMock, but you can also redesign your class and probably end up with better design (and then test it without problems using Mockito). I would encourage you to go with redesign, but I understand this is not always a viable option (e.g. working with legacy code, no time etc.)
Book author: Practical Unit Testing with TestNG and Mockito