我对嘲讽/抄袭有一个非常基本的了解。
在测试代码中创建存根时,如:
test h = mock(test);
when(h.hello()).thenReturn(10);
在源逻辑中我有这样的代码:
test src = new test();
src.hello();
现在将调用存根,因为我已经存根了hello方法或者由于实例不同,它是否会被存根?有没有办法存根该类的所有实例?
答案 0 :(得分:2)
您需要使用工厂模式并将模拟工厂注入到正在创建实例的类中。
因此,如果要为某些类Foo
编写测试,需要在其代码中的某处创建Bar
的实例,则需要在{BarFactory
中注入Foo
1}}。通过将BarFactory
传递给构造函数或set方法,或者使用像Guice这样的依赖注入框架,可以采用传统的方式进行注入。一个老式方式的简短例子:
class Foo {
private final BarFactory mFactory;
public Foo(BarFactory factory) {
mFactory = factory;
}
public void someMethodThatNeedsABar() {
Bar bar = mFactory.create();
}
}
现在,在您的测试类中,您可以注入一个可以生成BarFactory
的模拟实例的模拟Bar
:
Bar mockBar = mock(Bar.class);
BarFactory mockFactory = mock(BarFactory.class);
when(mockFactory.create()).thenReturn(mockBar);
Foo objectForTest = new Foo(mockFactory);
答案 1 :(得分:1)
编写可测试代码的更好方法不是在类代码中通过新运算符创建协作类,而是将协作类作为构造函数参数传递。
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);
// ...
答案 2 :(得分:1)
您需要使用模拟的实例来使存根工作。 干杯:)