简体   繁体   中英

How to partially mock a dependency abstract object in JMockit

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?

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM