Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Static Methods

As i did some research i have found out that PowerMock is able to mock static java methods.

Can someone explain (technically) what is PowerMock doing different than JUnit and others which can not or do not? And also why static methods are(were) causing issues when they are tried to mock?

thanks

like image 781
add9 Avatar asked Mar 23 '11 08:03

add9


1 Answers

http://blog.jayway.com/2009/05/17/mocking-static-methods-in-java-system-classes/

In order to mock an instance method, you can simply override it in a subclass. You can't do that with static methods because there's no "static polymorphism".

Powermock can do it because it works with bytecode, while other popular frameworks rely on polymorphism and create subclasses with CGLIB.

From the link: "Basically all standard mock frameworks use CGLib to create a mock object which means that they're based on a hierarchical model (CGLib creates a sub class of the class to test at run-time which is the actual mock object) instead of a delegation model which PowerMock uses through it's byte-code manipulation by delegating to the MockGateway."

like image 172
Konrad Garus Avatar answered Sep 28 '22 22:09

Konrad Garus