Mocking Static Methods using Groovy Add comment to Wiki View in Wiki Edit Wiki page Printable Version

Suppose you wish to test a class which is dependent on a static call. Is there a way to mock out that call?

Yes, there are two suggested approaches:

  • Using EMC
  • Using JMockit (requires Java 6)

Using EMC

Here we are calling Arrays.sort() directly - normally that would be the problematic code within your class under test.

More details about this approach: ExpandoMetaClass - Adding static methods

Using JMockit

If you are in a position to use Java 6, you should also consider using JMockit.

Where MockArrays is the following Java class:

We use a Java class here because otherwise JMockit tries to replace other GroovyObject methods (e.g. getMetaClass, invokeMethod, ...) and won't find them inside the java.util.Arrays class. Obviously, if your redefining a Groovy class, you can use another Groovy class.

More details: Using JMockit with Groovy.



Results of your search request can come from various sources: the Groovy website itself, the JIRA issues, the API documentation, as well as a few other interesting Groovy-related blogs.

  By  -  pages  -  views  - last modified