如何模拟最终对象的外部依赖关系? [英] How to mock external dependencies for final objects?

查看:71
本文介绍了如何模拟最终对象的外部依赖关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class A{
   private final B b;
   public void meth() {
      //Some code
      Integer a = b.some_method(a,fun(b));
      //Some code
   }
   private fun(int b) {
     return b;
   }
}
 when(b.some_method(anyInt(),anyInt())).thenReturn(100)

在编写类A的单元测试时如何模拟外部依赖关系.当我以上述方式模拟依赖关系时,"a"的值未按预期分配给100.

How to mock the externally dependency when writing unit tests for class A. When i mock dependency in the above way, the value of "a" is not getting assigned to 100 as expected.

推荐答案

实际上,雅库布的答案是正确的.也许您需要一个例子来了解如何做.检查我的示例的主要方法和构造器.

Actually the answer of Jakub is correct. Maybe you need an example to understand how to do it. Check the main method and the contructor of my example.

public class A {
    private final B b;

    public A(B b) {
        this.b = b;
    }

    public void meth() {
        //Some code
        Integer a = b.some_method(5,fun(5));
        //Some code
        System.out.println(a);
    }
    private int fun(int b) {
        return b;
    }

    public static void main(String[] args) {
        B b = Mockito.mock(B.class);

        when(b.some_method(anyInt(), anyInt())).thenReturn(100);

        new A(b).meth();
    }

}

使用构造函数,您必须将M设置为B(请参见main方法的最后第三行). 当您运行main方法时,您将看到System.out的输出,它是100.

With the constructor you have to set B with your mock (see the last third line in the main method). When you run the main method you will see the output of the System.out and it is 100.

这篇关于如何模拟最终对象的外部依赖关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆