[英]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.