jmock mocking a static method

前端 未结 3 1065
-上瘾入骨i
-上瘾入骨i 2020-12-04 01:27

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

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-04 02:18

    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 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.

提交回复
热议问题