[英]why cannot we create spy for Parameterized Constructor using Mockito
我的代码中只有参数化构造函数,我需要通过它注入。
我想间谍参数化构造函数注入模拟对象作为我的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
其中B
和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
B
和C
是使用参数化构造函数在类A
注入的模拟对象。 A
名为spyA
的spy
。 A
类中受保护方法method2
的返回值来检查spy
是否真的有效,如果spyA
不是A
的实际spy
, A
是不可能的。 听起来你可能错过了依赖注入解决方案。 Mockito非常适合与你的DI一起注射嘲笑。 例如,您可以使用CDI,使用@Inject
注释Notification
和EntryService
成员,在测试中为两者声明@Mock
s,然后让Mockito将这些注入您的RegDao
进行测试。
这是我认为你试图运行的测试的工作模型:
import static org.junit.Assert.assertEquals;
import javax.inject.Inject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class MockitoSpyInjection {
static class Notification { }
static class EntryService { }
static class RegDao {
@Inject
Notification foo;
@Inject
EntryService bar;
public RegDao() {
}
public RegDao(Notification foo, EntryService bar) {
this.foo = foo;
this.bar = bar;
}
public Notification getFoo() {
return foo;
}
public EntryService getBar() {
return bar;
}
}
@Mock
Notification foo;
@Mock
EntryService bar;
@Spy
@InjectMocks
RegDao dao;
@Test
public void test() {
assertEquals(foo, dao.getFoo());
assertEquals(bar, dao.getBar());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.