Search code examples
javaclassmockingjmockit

Mocking class with existing class in JMockit (replacement for `redefineMethods`)


I've got two classes as input and want to mock one with the other. That used to be very simple in JMockit, one just called

Mockit.redefineMethods(originalClass, mockingClass);

But in version 0.999 this deprecated method was removed. I need features of a newer version of JMockit, so I cannot use the older versions any more.

I guess from the documentation in the deprecation message that using the proposed "modern" way to do it would be to define a MockUp<originalClass> and use this as the mockingClass.

Unfortunately, I get both values as input parameters at runtime (declared as class<?>), so creating a class is not an option.

Is there any way to emulate what Mockit.redefineMethods() has done before version 0.999, even if it might be not the most elegant solution to address this issue?

EDIT

What I get as input is a Map<Class<?>, Class<?>> mockedClasses of classes to be mocked pointing to classes mocking them. These are then iterated over and passed to Mockit:

for (Map.Entry<Class<?>, Class<?>> entry : mockedClasses.entrySet()) {
  Mockit.redefineMethods(entry.getKey(), entry.getValue());
}

After that, the test code is executed, then the mocking is disabled again, using restoreOriginalDefinition() instead of redefineMethods() in a similar way.


Solution

  • Ok, the question is clearer now. And the answer is that there is no way to mock a class with another arbitrary class; you have to define the mock-up class as a subclass of MockUp. The very old Mockit.redefineMethods(Class, Class) (removed from the API 4.5+ years ago) only accepted arbitrary classes because that initial API also supported Java 1.4 for test code (which is no longer supported since 0.999, which required generics and/or annotations).