我有以下類結構。
public interface Foo<T extends Bar>{
Optional<T> find();
}
public class A extends Bar{}
public class B extends Bar{}
@Service
@RequiredArgsConstructor
public class C{
Foo<A> a;
Foo<B> b;
B bInstance = b.find();
}
public class CTest{
@Mock
Foo<A> a;
@Mock
Foo<B> b;
@InjectMocks
C c;
@Test
public void testSomething(){
when(a.someMethod()).thenReturn(someVariable);
when(b.someMethod()).thenReturn(someOtherVariable);
}
}
然后也許我在 C 類中有一些代碼,例如:
B bInstance = b.find();
這里的問題是,當呼叫 find 時,它從類 A 而不是 B 回傳一個新實體,即來自模擬 a 而不是模擬 b 的變數。因此,之后我得到一個 ClassLoadException 做一些作業。
這是否應該按預期作業,還是由模擬來自 2 個不同菱形運算子類的同一類 (Foo) 的 2 個變數引起的問題(如何呼叫?)(A 和 B)Mockito 無法解釋?我在這里錯過了其他東西嗎?這可能沒有足夠的資訊來進行后續作業,但希望我有一些概念誤解并且可以輕松修復。
提前致謝!
uj5u.com熱心網友回復:
我會自己創建測驗物件
public class CTest{
@Mock
Foo<A> a;
@Mock
Foo<B> b;
// @InjectMocks since it is not working for you, lets skip it
C service;
@Before
public void setup(){
service=new C(a,b);
}
@Test
public void testSomething(){
when(a.someMethod()).thenReturn(someVariable);
when(b.someMethod()).thenReturn(someOtherVariable);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/461429.html
