【问题标题】:What are the differences between @Mocked, @Injectable, and @Capturing?@Mocked、@Injectable 和 @Capturing 之间有什么区别?
【发布时间】:2019-02-16 15:37:38
【问题描述】:

首先,我定义一个类,比如说Robot

public class Robot {

    private Vision vision;

    public Object recognizeObject(List<List<Integer>> frames) {
        vision = new Vision();
        return vision.recognize(frames);
    }
}

Robot 的类有几个依赖项,其中之一是Vision

public class Vision {

    public Object recognize(List<List<Integer>> frames) {
        // do magic stuff, but return dummy stuff
        return null;
    }

}

然后在测试类中,我简单测试一下recognize()的调用。

@RunWith(JMockit.class)
public class RobotTest {

    @Test
    public void recognizeObjectWithMocked(@Mocked final Vision vision) {
        List<List<Integer>> frames = new ArrayList<>();
        vision.recognize(frames);

        new Verifications() {{
            vision.recognize((List<List<Integer>>) any);
            times = 1;
        }};
    }

    @Test
    public void recognizeObjectWithInjectable(@Injectable final Vision vision) {
        List<List<Integer>> frames = new ArrayList<>();
        vision.recognize(frames);

        new Verifications() {{
            vision.recognize((List<List<Integer>>) any);
            times = 1;
        }};
    }

    @Test
    public void recognizeObjectWithCapturing(@Capturing final Vision vision) {
        List<List<Integer>> frames = new ArrayList<>();
        vision.recognize(frames);

        new Verifications() {{
            vision.recognize((List<List<Integer>>) any);
            times = 1;
        }};
    }
}

基于这些测试,我认为@Mocked@Injectable@Capturing可以互换使用。

  • 对吗?

  • 如果答案是否定的,那么是否有任何情况只 @Mocked/@Injectable/@Capturing 是可能的,不能被替换 另一个?

【问题讨论】:

    标签: java unit-testing jmockit


    【解决方案1】:
    • @Injectable 模拟单个实例(例如测试方法的参数)。并非每个实例都在测试上下文中使用。
    • @Mocked 将在测试上下文中创建的每个实例上模拟所有类方法和构造函数。
    • @Capturing@Mocked 基本相同,但它将 mocking 扩展到注解类型的每个子类型(方便!)。

    @Injectable 的另一个区别是,只有标有此注解的字段才会考虑在 @Tested 实例中进行注入。

    现在应该很清楚区别了。

    【讨论】:

      猜你喜欢
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 2015-05-08
      • 2018-12-23
      • 2010-11-07
      • 2014-07-20
      • 2011-03-01
      相关资源
      最近更新 更多