I'm still learning mockito, and now I'm teaching how to introduce ridicule.
I have an object under test with a specific method that depends on other objects. These objects, in turn, depend on other objects. I want to mock certain things and use them in all cases at runtime - in the entire method control flow.
For example, suppose classes exist such as:
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); } }
I need to write test code with parts in rows:
.... @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); }
Whenever apple.price () is called, I want my breadboard apple to be used. Is it possible?
EDIT:
Important Note ...
the class containing the object I want to make fun of has a customization tool for this object. However, I have no help for this class at the level I'm testing. So, following the example, although ProductManager has a suite for Apple, I have no way to get the ProductManager from the GroceryStore object.
gMale source share