我的代码中只有参数化构造函数,我需要通过它注入。
我想监视参数化构造函数以注入模拟对象作为我的 junit 的依赖项。
public RegDao(){
//original object instantiation here
Notification ....
EntryService .....
}
public RegDao(Notification notification , EntryService entry) {
// initialize here
}
we have something like below :
RegDao dao = Mockito.spy(RegDao.class);
但是我们是否有一些可以在构造函数中注入模拟对象并监视它的东西?
您可以通过在 junit 中使用参数化构造函数实例化主类,然后从中创建间谍来实现此目的。
假设您的主课是A
. Where B
and C
是它的依赖项
public class A {
private B b;
private C c;
public A(B b,C c)
{
this.b=b;
this.c=c;
}
void method() {
System.out.println("A's method called");
b.method();
c.method();
System.out.println(method2());
}
protected int method2() {
return 10;
}
}
然后您可以使用参数化类为此编写 junit,如下所示
@RunWith(MockitoJUnitRunner.class)
public class ATest {
A a;
@Mock
B b;
@Mock
C c;
@Test
public void test() {
a=new A(b, c);
A spyA=Mockito.spy(a);
doReturn(20).when(spyA).method2();
spyA.method();
}
}
测试类的输出
A's method called
20
- Here
B
and C
是您在类中注入的模拟对象A
使用参数化构造函数。
- 然后我们创建了一个
spy
of A
called spyA
.
- 我们检查了是否
spy
实际上是通过修改受保护方法的返回值来起作用的method2
在班上A
如果spyA
不是实际的spy
of A
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)