問題描述
我的代碼中只有參數化的構造函數,我需要通過它進行注入.
I have only parameterized constructor in my code and i need to inject through it.
我想監視參數化構造函數以注入模擬對象作為我的 junit 的依賴項.
I want to spy parameterized constructor to inject mock object as dependency for my 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);
但是我們有什么東西可以讓我在構造函數中注入模擬對象并監視它嗎?
But do we have something that i can inject mocked object in the Constructor and spy it?.
推薦答案
您可以通過在 junit 中使用參數化構造函數實例化您的主類,然后從中創建一個間諜來做到這一點.
You can do that by instantiating your main class with parametrized constructor in your junit and then creating a spy from it.
假設您的主類是A
.其中 B
和 C
是它的依賴項
Let's suppose your main class is A
. Where B
and C
are its dependencies
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
Then you can write junit for this using your parametrized class as below
@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
中的模擬對象. - 然后我們創建了一個名為
spyA
的A
的spy
. - 我們通過修改類
A
中受保護方法method2
的返回值來檢查spy
是否真的有效,這不可能如果spyA
不是A
的實際spy
.
- Here
B
andC
are mocked object that you injected in your classA
using parametrized constructor. - Then we created a
spy
ofA
calledspyA
. - We checked if
spy
is really working by modifying the return value of a protected methodmethod2
in classA
which could not have been possible ifspyA
was not an actualspy
ofA
.
這篇關于為什么我們不能使用 Mockito 為參數化構造函數創建間諜的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!