Jmockit autowire dependendency with mocks injected

22 Views Asked by At

I'm having a situation in which I have certain mocking and utilities (not static methods, but certain manipulations relying on mocks).

Lets say like this,

class MyReusableClassForTesting {

@Mocked
private ClassA attribute;

// And some more @Mocked and methods that are relying on the mocks.
}

I want to use the instance of MyReusableClass in my test classes with mocks injected.

class MyTestClass {

// Need this be a real instance with mocks injected inside it
private MyReusableClassForTesting instance;
}

I tried with @Mocked, @Capturing, @Tested and @Injectable. None of them seem to work. Any idea, how can I make this work with Jmockit?

1

There are 1 best solutions below

0
Jeff Bennett On

You would normally just do this:

class MyTestClass {
    // Need this be a real instance with mocks injected inside it
    @Tested
    public MyReusableClassForTesting instance;
}

If the 'instance' constructor takes arguments, or if it has things Autowired, then add (possibly multiple) at the test-class level:

@Injectable
protected ClassA attribute;

To make sure JMockit is working, I usually add a simple test

@Test
public void testCtor() {
    assertNotNull(instance);
}

JMockit will take care of creating the 'instance' based on @Tested and @Injectable. The only way this test fails is if JMockit isn't working - i.e. you forgot to add the javaagent. You generally need the javaagent in BOTH your build script (build.gradle or pom.xml) as well as when you run the test manually from your IDE.