我仍在學習mockito,現在我正在學習如何注入mock。Mockito:在整個控制流中注入模擬
我有一個測試對象與依賴於其他對象的特定方法。這些對象又取決於其他對象。我想嘲笑某些事情,並在執行過程中隨處使用這些模擬 - 貫穿方法的控制流程。
例如,假設有像類:
public class GroceryStore {
public double inventoryValue = 0.0;
private shelf = new Shelf(5);
public void takeInventory() {
for(Item item : shelf) {
inventoryValue += item.price();
}
}
}
public class Shelf extends ArrayList<Item> {
private ProductManager manager = new ProductManager();
public Shelf(int aisleNumber){
super(manager.getShelfContents(aisleNumber);
}
}
public class ProductManager {
private Apple apple;
public void setApple(Apple newApple) {
apple = newApple;
}
public Collection<Item> getShelfContents(int aisleNumber) {
return Arrays.asList(apple, apple, apple, apple, apple);
}
}
我需要編寫測試代碼與沿着線的部分:
....
@Mock
private Apple apple;
...
when(apple.price()).thenReturn(10.0);
...
...
@InjectMocks
private GroceryStore store = new GroceryStore();
...
@Test
public void testTakeInventory() {
store.takeInventory();
assertEquals(50.0, store.inventoryValue);
}
每當apple.price()被調用時,我想我的嘲笑蘋果是使用的。這可能嗎?
編輯:
重要提示...
包含我想嘲笑確實有該對象的二傳手對象的類。但是,我在測試的級別上並沒有真正掌握該類。因此,遵循這個例子,儘管ProductManager有一個Apple的setter,但我沒有辦法從GroceryStore對象獲取ProductManager。
我認爲你必須創建蘋果,然後模擬工廠工廠 – 2010-10-15 12:29:19
@Alois:沿着這些線可能是正確的,但。 。 。如何讓ProductManager使用工廠(從GroceryStore的單元測試中)? – gMale 2010-10-15 12:31:51
用ProductManager中的setter來定義工廠。你使用任何DI(依賴注入)框架?例如春天或者guice – 2010-10-15 12:38:10