jmock mocking a static method

假装没事ソ 提交于 2019-11-27 16:03:20

We don't support mocking static methods in jMock because it doesn't fit our design approach. We prefer not to use static methods for significant features that can affect the state of the system. We tend to use them just to support the OO code and make it more readable. That's why we view mocking a static methods as a hint that there's a problem. One exception is where it's in a third-party library, but we would probably wrap that in something more object-oriented anyway.

JMockit is another toolkit which allows mocking of static methods (as well as final methods, constructors, etc.).

I don't see any problem with the judicious use of static methods when designing an otherwise OO solution.

For example, one pattern/idiom I like to use is the static facade, particularly to provide a simpler and easier to use API to the persistence subsystem in a business application. In my opinion, no other solution is more elegant than something like:


    List<Person> peopleAboveAge = 
        find("select p from Person p where p.age >= ?", age);

where the find method is statically imported from a PersistenceFacade class which defines only static methods, and encapsulates how to obtain the proper Session/EntityManager instance. This solution is unit-testing friendly and flexible. I used it in a business application which had 500+ persistent entities, using Hibernate. The static facade helped when we migrated from Hibernate 2 to Hibernate 3, when we migrated from Oracle to Sybase and then back to Oracle, and when we started using JPA annotations instead of "hbm.xml" files for ORM mapping.

Powermock is an extension to EasyMock that allows mocking of static methods.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!