Search code examples
javaunit-testingjmockit

Create dummy objects for classes using JMockit


I'd like to create dummy objects (see definition here) using JMockit.

These objects are required as nonnull constructor arguments, but aren't needed for the specific unittest. Because the constructor might check the parameter (e. g. using Objects.requireNonNull), the dummy can't just be null.

I'd like to use something like

new ObjectWithUnusedDependency(dummy());

where dummy() creates a dummy object.

Using

public static <T> T dummy() {
    return new MockUp<T>() {}.getMockInstance();
}

this might work if T is an interface, but for classes getMockInstance returns null.

It would be nice, if the test would fail when a method is invoked on such a dummy object.

Is there a way to accomplish this using JMockit?


Solution

  • This is very easy to do with JMockit. Simply declare a mock field or mock parameter of the desired type, and pass it to the code under test. For example:

    @Test
    public void myTest(@Injectable SomeClass dummy)
    {
        new ObjectWithUnusedDependency(dummy).doSomething();
    }
    

    Works for any reference type, including final classes, abstract classes, interfaces, enums, etc.

    If, in addition, you want the test to fail in case any methods get called on the dummy object, a "full verification" needs to be added:

    @Test
    public void myTest(@Injectable SomeClass dummy)
    {
        new ObjectWithUnusedDependency(dummy).doSomething();
    
        new FullVerifications(dummy) {};
    }