How to partially mock a dependency abstract object in JMockit

553 views Asked by At

I have abstract class D which is a dependency of the tested class T.

The test class:

public class T_Test {
    @Tested T tested;

    D dependency;

    public void test() {
        dependency.doSomething();
        tested.testedMethod(dependency);
    }
}

I want the dependency.doSomething() will run the real code of this method, but that the abstract methods will be mocked.

  1. If I run the test as is, I obviously get NullPointerException for using the uninitialized dependency.

  2. If I add the @Mocked annotation to the D dependency line, all the methods in D are mocked, so d.doSomething() doesn't do what it's supposed to do.

  3. If I keep the @Mocked annotation and also add an empty NonStrictExpectations block at the beginning of the test method, in order to have partial mock, either like this:

    new NonStrictExpectations(D.class) {};
    

    or like this:

    new NonStrictExpectations(d) {};
    

    I get java.lang.IllegalArgumentException: Already mocked: class D.

  4. If I keep the NonStrictExpectations block and remove the @Mocked annotation, again I get NullPointerException for using the uninitialized dependency.

So how can I partially mock this dependency abstract class?

1

There are 1 answers

0
Dikla On BEST ANSWER

Using the @Capturing annotation on the dependency achieves this. No need to add an empty expectations block; only the abstract methods will be mocked.

public class T_Test {
    @Tested T tested;

    @Capturing D dependency;

    public void test() {
        dependency.doSomething();
        tested.testedMethod(dependency);
    }
}