jmock mocking a static method
Asked Answered
O

3

11

I have a static method in my code that I would like somehow to mock.

I am using jmock.

One way I suppose I could do this is to have "wrapper class" around the static method and mock this but I was hoping for a better solution.

I am going about this the wrong way?

FEEDBACK:

I was going to have a interface and class that had a method that just called the static method. It would allow me to mock the logic by just mocking the call to this wrapper class. (I feel dirty even talking about it :) )

Outage answered 20/10, 2008 at 15:26 Comment(1)
See related question How to mock with static methods.Into
F
8

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.

Fallen answered 21/5, 2009 at 12:51 Comment(0)
D
5

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.

Dutyfree answered 27/6, 2009 at 17:35 Comment(0)
Z
2

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

Zachariahzacharias answered 4/11, 2008 at 3:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.