問題描述
我的代碼中只有參數(shù)化的構(gòu)造函數(shù),我需要通過它進(jìn)行注入.
I have only parameterized constructor in my code and i need to inject through it.
我想監(jiān)視參數(shù)化構(gòu)造函數(shù)以注入模擬對象作為我的 junit 的依賴項(xiàng).
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);
但是我們有什么東西可以讓我在構(gòu)造函數(shù)中注入模擬對象并監(jiān)視它嗎?
But do we have something that i can inject mocked object in the Constructor and spy it?.
推薦答案
您可以通過在 junit 中使用參數(shù)化構(gòu)造函數(shù)實(shí)例化您的主類,然后從中創(chuàng)建一個(gè)間諜來做到這一點(diǎn).
You can do that by instantiating your main class with parametrized constructor in your junit and then creating a spy from it.
假設(shè)您的主類是A
.其中 B
和 C
是它的依賴項(xiàng)
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;
}
}
然后您可以使用下面的參數(shù)化類為此編寫 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
是您使用參數(shù)化構(gòu)造函數(shù)注入到您的類A
中的模擬對象. - 然后我們創(chuàng)建了一個(gè)名為
spyA
的A
的spy
. - 我們通過修改類
A
中受保護(hù)方法method2
的返回值來檢查spy
是否真的有效,這不可能如果spyA
不是A
的實(shí)際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
.
這篇關(guān)于為什么我們不能使用 Mockito 為參數(shù)化構(gòu)造函數(shù)創(chuàng)建間諜的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!