JMockit is a single class with a small set of static methods, which allow arbitrary methods and constructors of any other class to be replaced by mock implementations at runtime. It has the following features:
new SomeClass()calls throughout your code
Since JMockit depends on the JVM class redefinition mechanism exposed by java.lang.instrumentation, Groovy, JUnit or TestNG tests that use it must be run under a Java SE 5 VM. However, application and test code can still be compiled to older versions of the language.
The sections below illustrate using JMockit for the mocking parts of Using Testing Frameworks with Groovy.
We are going to consider how you might use JMockit as part of testing the Item Storer Example.
First we define the following class in a file called
We place this in a separate file rather than straight in the same script as the instrumentation classes in the JVM (which JMockit relies upon) don't know about classes compiled in memory by Groovy. They will look for replaced classes on the classpath.
Now, here is how we can test
If you recall from the example,
Storer does a
new GroovyReverser() call, so we use
Mockit.redefineMethods() to replace the original version with our mock version.