简体   繁体   English

如何在JMockit中部分模拟依赖项抽象对象

[英]How to partially mock a dependency abstract object in JMockit

I have abstract class D which is a dependency of the tested class T . 我有抽象类D ,它是经过测试的类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. 我希望dependency.doSomething()将运行此方法的实际代码,但是抽象方法将被模拟。

  1. If I run the test as is, I obviously get NullPointerException for using the uninitialized dependency . 如果按原样运行测试,则显然会因为使用未初始化的dependency收到NullPointerException

  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. 如果我添加@Mocked注释到D dependency线,在所有的方法D被嘲笑,所以d.doSomething()不会做它应该做的。

  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: 如果我保留@Mocked批注并在测试方法的开头添加一个空的NonStrictExpectations块,则可以进行部分模拟,如下所示:

     new NonStrictExpectations(D.class) {}; 

    or like this: 或像这样:

     new NonStrictExpectations(d) {}; 

    I get java.lang.IllegalArgumentException: Already mocked: class D . 我得到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 . 如果我保留NonStrictExpectations块并删除@Mocked批注,则再次会因使用未初始化的dependency得到NullPointerException

So how can I partially mock this dependency abstract class? 那么,如何部分模拟该依赖抽象类呢?

Using the @Capturing annotation on the dependency achieves this. 在依赖项上使用@Capturing批注可实现此目的。 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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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