...
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.
| Code Block |
|---|
// require(url:'https://jmockit.dev.java.net', jar='jmockit.jar')
// require(url:'https://jmockit.dev.java.net', jar='jmockit-asm2.jar')
// needs to be run with "-javaagent:jmockit.jar"
// and "-Xbootclasspath/a:jmockit.jar;.;jmockit-asm2.jar"
// The bootclasspath option is only required because we are mocking
// a class from the java.* package (part of the bootclasspath for Java)
import mockit.Mockit
// non-mocked first to show normal case
String[] things = ['dog', 'ant', 'bee', 'cat']
Arrays.sort(things)
println things // => {"ant", "bee", "cat", "dog"}
Mockit.redefineMethods(Arrays, MockArrays)
things = ['dog', 'ant', 'bee', 'cat']
Arrays.sort(things)
println things // => {"dog", "elk", "ape", "cat"}
|
...