繁体   English   中英

了解模拟/存根-Mockito

[英]Understanding mocking/stubbing - mockito

我对模拟/存根有非常基本的了解。

在测试代​​码中创建存根时,例如:

test h = mock(test);
when(h.hello()).thenReturn(10);

在源逻辑中,我有这样的代码:

test src = new test();
src.hello();

现在,因为我已经对hello方法进行了存根,所以存根将被调用;或者由于实例不同,它不会被存根吗? 有什么方法可以存根该类的所有实例吗?

您将需要使用工厂模式,并将模拟的工厂注入创建实例的类中。

因此,如果要为某些类Foo编写测试,而该类需要在其代码中的某个位置创建Bar实例,则需要将BarFactory注入Foo 通过将BarFactory传递到构造函数或set方法中,或使用诸如Guice的依赖项注入框架,注入可以通过老式的方式进行。 老式方式的简要示例:

class Foo {

    private final BarFactory mFactory;

    public Foo(BarFactory factory) {
        mFactory = factory;
    }

    public void someMethodThatNeedsABar() {
        Bar bar = mFactory.create();
    }

}

现在,在测试类中,您可以注入一个BarFactory ,该模型可以产生Bar BarFactory实例:

Bar mockBar = mock(Bar.class);
BarFactory mockFactory = mock(BarFactory.class);
when(mockFactory.create()).thenReturn(mockBar);
Foo objectForTest = new Foo(mockFactory);

编写可测试代码的更好方法不是通过新的运算符在类代码中创建协作类,而是将协作类作为构造函数参数传递。

class TestedClass{
private final Helper helper;
public TestedClass(Helper helper){
      this.helper = helper;
}

public aMethodUsesHelper(){
    //hello is weird name for method that returns int but it is link to your code
    int aVar =this.helper.hello();
    // ...
}
// ...

然后在测试课中:

Helper helper = mock(Helper.class);
when(helper.hello()).thenReturn(10);
TestedClass tested = new Tested(helper);
// ...

您需要使用模拟的实例来使存根正常工作。 干杯:)

暂无
暂无

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

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