Pra*_*eep 11 java junit4 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);
Run Code Online (Sandbox Code Playgroud)
但是我们有什么东西可以在构造函数中注入模拟对象并窥探它吗?
Dha*_*pil 23
您可以通过在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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用参数化类为此编写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();
}
}
Run Code Online (Sandbox Code Playgroud)
测试类的输出
A's method called
20
Run Code Online (Sandbox Code Playgroud)
B和C被嘲笑您在注射类物体A使用参数化的构造函数.spy的A叫spyA.spy通过修改method2类A中受保护方法的返回值来检查是否真正起作用,如果spyA不是实际的spy,那么这是不可能的A.| 归档时间: |
|
| 查看次数: |
8939 次 |
| 最近记录: |