Best Mockito code snippet using org.mockito.Mockito.atLeast
Source:InventoryAuthoritySystemTest.java  
1/*2 * Copyright 2014 MovingBlocks3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 *      http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package org.terasology.logic.inventory;17import org.junit.Before;18import org.junit.Test;19import org.mockito.Matchers;20import org.mockito.Mockito;21import org.mockito.internal.verification.AtLeast;22import org.mockito.internal.verification.Times;23import org.terasology.entitySystem.entity.EntityManager;24import org.terasology.entitySystem.entity.EntityRef;25import org.terasology.logic.inventory.action.GiveItemAction;26import org.terasology.logic.inventory.action.RemoveItemAction;27import org.terasology.logic.inventory.events.BeforeItemPutInInventory;28import org.terasology.logic.inventory.events.BeforeItemRemovedFromInventory;29import org.terasology.logic.inventory.events.InventorySlotChangedEvent;30import org.terasology.logic.inventory.events.InventorySlotStackSizeChangedEvent;31import java.util.Arrays;32import java.util.LinkedList;33import java.util.List;34import static junit.framework.Assert.assertNull;35import static org.junit.Assert.assertEquals;36import static org.junit.Assert.assertFalse;37import static org.junit.Assert.assertTrue;38/**39 */40public class InventoryAuthoritySystemTest {41    private InventoryAuthoritySystem inventoryAuthoritySystem;42    private EntityRef instigator;43    private EntityRef inventory;44    private InventoryComponent inventoryComp;45    private EntityManager entityManager;46    @Before47    public void setup() {48        inventoryAuthoritySystem = new InventoryAuthoritySystem();49        instigator = Mockito.mock(EntityRef.class);50        inventory = Mockito.mock(EntityRef.class);51        inventoryComp = new InventoryComponent(5);52        Mockito.when(inventory.getComponent(InventoryComponent.class)).thenReturn(inventoryComp);53        entityManager = Mockito.mock(EntityManager.class);54        inventoryAuthoritySystem.setEntityManager(entityManager);55    }56    @Test57    public void removePartOfStack() {58        ItemComponent itemComp = new ItemComponent();59        EntityRef item = Mockito.mock(EntityRef.class);60        setupItemRef(item, itemComp, 2, 10);61        inventoryComp.itemSlots.set(0, item);62        EntityRef itemCopy = Mockito.mock(EntityRef.class);63        ItemComponent itemCompCopy = new ItemComponent();64        setupItemRef(itemCopy, itemCompCopy, 2, 10);65        Mockito.when(entityManager.copy(item)).thenReturn(itemCopy);66        RemoveItemAction action = new RemoveItemAction(instigator, item, false, 1);67        inventoryAuthoritySystem.removeItem(action, inventory);68        assertEquals(1, itemComp.stackCount);69        assertEquals(1, itemCompCopy.stackCount);70        Mockito.verify(item, new AtLeast(0)).getComponent(ItemComponent.class);71        Mockito.verify(item, new AtLeast(0)).iterateComponents();72        Mockito.verify(item).saveComponent(itemComp);73        Mockito.verify(itemCopy, new AtLeast(0)).getComponent(ItemComponent.class);74        Mockito.verify(itemCopy, new AtLeast(0)).iterateComponents();75        Mockito.verify(itemCopy).saveComponent(itemCompCopy);76        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);77        Mockito.verify(inventory).send(Matchers.any(InventorySlotStackSizeChangedEvent.class));78        Mockito.verify(entityManager).copy(item);79        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item, itemCopy);80        assertTrue(action.isConsumed());81        assertEquals(itemCopy, action.getRemovedItem());82    }83    @Test84    public void removeWholeStack() {85        ItemComponent itemComp = new ItemComponent();86        EntityRef item = Mockito.mock(EntityRef.class);87        setupItemRef(item, itemComp, 2, 10);88        inventoryComp.itemSlots.set(0, item);89        RemoveItemAction action = new RemoveItemAction(instigator, item, false, 2);90        inventoryAuthoritySystem.removeItem(action, inventory);91        assertTrue(action.isConsumed());92        assertEquals(item, action.getRemovedItem());93        assertEquals(EntityRef.NULL, inventoryComp.itemSlots.get(0));94        Mockito.verify(item, new AtLeast(0)).getComponent(ItemComponent.class);95        Mockito.verify(item, new AtLeast(0)).exists();96        Mockito.verify(item, new AtLeast(0)).iterateComponents();97        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);98        Mockito.verify(inventory).saveComponent(inventoryComp);99        Mockito.verify(inventory, new Times(2)).send(Matchers.any(BeforeItemRemovedFromInventory.class));100        Mockito.verify(inventory, new Times(2)).send(Matchers.any(InventorySlotChangedEvent.class));101        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item);102    }103    @Test104    public void removePartOfStackWithDestroy() {105        ItemComponent itemComp = new ItemComponent();106        EntityRef item = Mockito.mock(EntityRef.class);107        setupItemRef(item, itemComp, 2, 10);108        inventoryComp.itemSlots.set(0, item);109        RemoveItemAction action = new RemoveItemAction(instigator, item, true, 1);110        inventoryAuthoritySystem.removeItem(action, inventory);111        assertEquals(1, itemComp.stackCount);112        Mockito.verify(item, new AtLeast(0)).getComponent(ItemComponent.class);113        Mockito.verify(item).saveComponent(itemComp);114        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);115        Mockito.verify(inventory).send(Matchers.any(InventorySlotStackSizeChangedEvent.class));116        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item);117        assertTrue(action.isConsumed());118        assertNull(action.getRemovedItem());119    }120    @Test121    public void removeWholeStackWithDestroy() {122        ItemComponent itemComp = new ItemComponent();123        EntityRef item = Mockito.mock(EntityRef.class);124        setupItemRef(item, itemComp, 2, 10);125        inventoryComp.itemSlots.set(0, item);126        RemoveItemAction action = new RemoveItemAction(instigator, item, true, 2);127        inventoryAuthoritySystem.removeItem(action, inventory);128        assertTrue(action.isConsumed());129        assertNull(action.getRemovedItem());130        assertEquals(EntityRef.NULL, inventoryComp.itemSlots.get(0));131        Mockito.verify(item, new AtLeast(0)).getComponent(ItemComponent.class);132        Mockito.verify(item, new AtLeast(0)).exists();133        Mockito.verify(item).destroy();134        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);135        Mockito.verify(inventory).saveComponent(inventoryComp);136        Mockito.verify(inventory, new Times(2)).send(Matchers.any(BeforeItemRemovedFromInventory.class));137        Mockito.verify(inventory, new Times(2)).send(Matchers.any(InventorySlotChangedEvent.class));138        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item);139    }140    @Test141    public void removeOverOneStack() {142        EntityRef item1 = Mockito.mock(EntityRef.class);143        ItemComponent itemComp1 = new ItemComponent();144        setupItemRef(item1, itemComp1, 2, 10);145        inventoryComp.itemSlots.set(0, item1);146        EntityRef item2 = Mockito.mock(EntityRef.class);147        ItemComponent itemComp2 = new ItemComponent();148        setupItemRef(item2, itemComp2, 2, 10);149        inventoryComp.itemSlots.set(1, item2);150        RemoveItemAction action = new RemoveItemAction(instigator, Arrays.asList(item1, item2), false, 3);151        inventoryAuthoritySystem.removeItem(action, inventory);152        assertEquals(EntityRef.NULL, inventoryComp.itemSlots.get(0));153        assertEquals(3, itemComp1.stackCount);154        assertEquals(1, itemComp2.stackCount);155        assertTrue(action.isConsumed());156        assertEquals(item1, action.getRemovedItem());157        Mockito.verify(item1, new AtLeast(0)).getComponent(ItemComponent.class);158        Mockito.verify(item1, new AtLeast(0)).exists();159        Mockito.verify(item1, new AtLeast(0)).iterateComponents();160        Mockito.verify(item1).saveComponent(itemComp1);161        Mockito.verify(item2, new AtLeast(0)).getComponent(ItemComponent.class);162        Mockito.verify(item2, new AtLeast(0)).iterateComponents();163        Mockito.verify(item2).saveComponent(itemComp2);164        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);165        Mockito.verify(inventory).saveComponent(inventoryComp);166        Mockito.verify(inventory, new Times(3)).send(Matchers.any(BeforeItemRemovedFromInventory.class));167        Mockito.verify(inventory, new Times(3)).send(Matchers.any(InventorySlotChangedEvent.class));168        Mockito.verify(inventory, new Times(3)).send(Matchers.any(InventorySlotStackSizeChangedEvent.class));169        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item1, item2);170    }171    @Test172    public void removeOverOneStackWithDestroy() {173        EntityRef item1 = Mockito.mock(EntityRef.class);174        ItemComponent itemComp1 = new ItemComponent();175        setupItemRef(item1, itemComp1, 2, 10);176        inventoryComp.itemSlots.set(0, item1);177        EntityRef item2 = Mockito.mock(EntityRef.class);178        ItemComponent itemComp2 = new ItemComponent();179        setupItemRef(item2, itemComp2, 2, 10);180        inventoryComp.itemSlots.set(1, item2);181        RemoveItemAction action = new RemoveItemAction(instigator, Arrays.asList(item1, item2), true, 3);182        inventoryAuthoritySystem.removeItem(action, inventory);183        assertEquals(EntityRef.NULL, inventoryComp.itemSlots.get(0));184        assertEquals(1, itemComp2.stackCount);185        assertTrue(action.isConsumed());186        assertNull(action.getRemovedItem());187        Mockito.verify(item1, new AtLeast(0)).getComponent(ItemComponent.class);188        Mockito.verify(item1, new AtLeast(0)).exists();189        Mockito.verify(item1, new AtLeast(0)).iterateComponents();190        Mockito.verify(item1).destroy();191        Mockito.verify(item2, new AtLeast(0)).getComponent(ItemComponent.class);192        Mockito.verify(item2, new AtLeast(0)).iterateComponents();193        Mockito.verify(item2).saveComponent(itemComp2);194        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);195        Mockito.verify(inventory).saveComponent(inventoryComp);196        Mockito.verify(inventory, new Times(3)).send(Matchers.any(BeforeItemRemovedFromInventory.class));197        Mockito.verify(inventory, new Times(3)).send(Matchers.any(InventorySlotChangedEvent.class));198        Mockito.verify(inventory, new Times(3)).send(Matchers.any(InventorySlotStackSizeChangedEvent.class));199        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item1, item2);200    }201    @Test202    public void removeWholeStackWithVeto() {203        ItemComponent itemComp = new ItemComponent();204        EntityRef item = Mockito.mock(EntityRef.class);205        setupItemRef(item, itemComp, 2, 10);206        inventoryComp.itemSlots.set(0, item);207        Mockito.when(inventory.send(Matchers.any(BeforeItemRemovedFromInventory.class))).then(208                invocation -> {209                    BeforeItemRemovedFromInventory event = (BeforeItemRemovedFromInventory) invocation.getArguments()[0];210                    event.consume();211                    return null;212                }213        );214        RemoveItemAction action = new RemoveItemAction(instigator, item, true, 2);215        inventoryAuthoritySystem.removeItem(action, inventory);216        assertFalse(action.isConsumed());217        assertNull(action.getRemovedItem());218        Mockito.verify(item, new AtLeast(0)).getComponent(ItemComponent.class);219        Mockito.verify(item, new AtLeast(0)).exists();220        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);221        Mockito.verify(inventory).send(Matchers.any(BeforeItemRemovedFromInventory.class));222        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item);223    }224    @Test225    public void addItemToEmpty() {226        ItemComponent itemComp = new ItemComponent();227        EntityRef item = Mockito.mock(EntityRef.class);228        setupItemRef(item, itemComp, 2, 10);229        GiveItemAction action = new GiveItemAction(instigator, item);230        inventoryAuthoritySystem.giveItem(action, inventory);231        Mockito.verify(item, new AtLeast(0)).getComponent(ItemComponent.class);232        Mockito.verify(item, new AtLeast(0)).exists();233        Mockito.verify(item).saveComponent(itemComp);234        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);235        Mockito.verify(inventory).saveComponent(inventoryComp);236        Mockito.verify(inventory, new Times(2)).send(Matchers.any(BeforeItemPutInInventory.class));237        Mockito.verify(inventory, new Times(2)).send(Matchers.any(InventorySlotChangedEvent.class));238        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item);239        assertEquals(item, inventoryComp.itemSlots.get(0));240        assertTrue(action.isConsumed());241    }242    @Test243    public void addItemToPartial() {244        ItemComponent itemComp = new ItemComponent();245        EntityRef item = Mockito.mock(EntityRef.class);246        setupItemRef(item, itemComp, 2, 10);247        ItemComponent partialItemComp = new ItemComponent();248        EntityRef partialItem = Mockito.mock(EntityRef.class);249        setupItemRef(partialItem, partialItemComp, 2, 10);250        inventoryComp.itemSlots.set(0, partialItem);251        GiveItemAction action = new GiveItemAction(instigator, item);252        inventoryAuthoritySystem.giveItem(action, inventory);253        Mockito.verify(item, new AtLeast(0)).getComponent(ItemComponent.class);254        Mockito.verify(item, new AtLeast(0)).exists();255        Mockito.verify(item, new AtLeast(0)).iterateComponents();256        Mockito.verify(item).destroy();257        Mockito.verify(partialItem, new AtLeast(0)).getComponent(ItemComponent.class);258        Mockito.verify(partialItem, new AtLeast(0)).exists();259        Mockito.verify(partialItem, new AtLeast(0)).iterateComponents();260        Mockito.verify(partialItem).saveComponent(partialItemComp);261        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);262        Mockito.verify(inventory).send(Matchers.any(InventorySlotStackSizeChangedEvent.class));263        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item, partialItem);264        assertEquals(partialItem, inventoryComp.itemSlots.get(0));265        assertEquals(4, partialItemComp.stackCount);266        assertTrue(action.isConsumed());267    }268    @Test269    public void addItemToPartialAndOverflow() {270        ItemComponent itemComp = new ItemComponent();271        EntityRef item = Mockito.mock(EntityRef.class);272        setupItemRef(item, itemComp, 2, 10);273        ItemComponent partialItemComp = new ItemComponent();274        EntityRef partialItem = Mockito.mock(EntityRef.class);275        setupItemRef(partialItem, partialItemComp, 9, 10);276        inventoryComp.itemSlots.set(0, partialItem);277        GiveItemAction action = new GiveItemAction(instigator, item);278        inventoryAuthoritySystem.giveItem(action, inventory);279        Mockito.verify(item, new AtLeast(0)).getComponent(ItemComponent.class);280        Mockito.verify(item, new AtLeast(0)).exists();281        Mockito.verify(item, new AtLeast(0)).iterateComponents();282        Mockito.verify(item).saveComponent(itemComp);283        Mockito.verify(partialItem, new AtLeast(0)).getComponent(ItemComponent.class);284        Mockito.verify(partialItem, new AtLeast(0)).exists();285        Mockito.verify(partialItem, new AtLeast(0)).iterateComponents();286        Mockito.verify(partialItem).saveComponent(partialItemComp);287        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);288        Mockito.verify(inventory).saveComponent(inventoryComp);289        Mockito.verify(inventory, new Times(3)).send(Matchers.any(InventorySlotStackSizeChangedEvent.class));290        Mockito.verify(inventory, new Times(3)).send(Matchers.any(InventorySlotChangedEvent.class));291        Mockito.verify(inventory, new Times(3)).send(Matchers.any(BeforeItemPutInInventory.class));292        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item, partialItem);293        assertEquals(partialItem, inventoryComp.itemSlots.get(0));294        assertEquals(item, inventoryComp.itemSlots.get(1));295        assertEquals(10, partialItemComp.stackCount);296        assertEquals(1, itemComp.stackCount);297        assertTrue(action.isConsumed());298    }299    @Test300    public void addItemToEmptyWithVeto() {301        ItemComponent itemComp = new ItemComponent();302        EntityRef item = Mockito.mock(EntityRef.class);303        setupItemRef(item, itemComp, 2, 10);304        Mockito.when(inventory.send(Matchers.any(BeforeItemPutInInventory.class))).then(305                invocation -> {306                    BeforeItemPutInInventory event = (BeforeItemPutInInventory) invocation.getArguments()[0];307                    event.consume();308                    return null;309                }310        );311        GiveItemAction action = new GiveItemAction(instigator, item);312        inventoryAuthoritySystem.giveItem(action, inventory);313        Mockito.verify(item, new AtLeast(0)).getComponent(ItemComponent.class);314        Mockito.verify(item, new AtLeast(0)).exists();315        Mockito.verify(inventory, new AtLeast(0)).getComponent(InventoryComponent.class);316        Mockito.verify(inventory, new Times(5)).send(Matchers.any(BeforeItemPutInInventory.class));317        Mockito.verifyNoMoreInteractions(instigator, inventory, entityManager, item);318        assertFalse(action.isConsumed());319    }320    private void setupItemRef(EntityRef item, ItemComponent itemComp, int stackCount, int stackSize) {321        itemComp.stackCount = (byte) stackCount;322        itemComp.maxStackSize = (byte) stackSize;323        itemComp.stackId = "stackId";324        Mockito.when(item.exists()).thenReturn(true);325        Mockito.when(item.getComponent(ItemComponent.class)).thenReturn(itemComp);326        Mockito.when(item.iterateComponents()).thenReturn(new LinkedList<>());327    }328    private EntityRef createItem(String stackId, int stackCount, int stackSize) {329        ItemComponent itemComp = new ItemComponent();330        itemComp.stackCount = (byte) stackCount;331        itemComp.maxStackSize = (byte) stackSize;332        itemComp.stackId = stackId;333        EntityRef item = Mockito.mock(EntityRef.class);334        Mockito.when(item.exists()).thenReturn(true);335        Mockito.when(item.getComponent(ItemComponent.class)).thenReturn(itemComp);336        Mockito.when(item.iterateComponents()).thenReturn(new LinkedList<>());337        return item;338    }339    @Test340    public void testMoveItemToSlotsWithSplittingToMultipleStacks() {341        int stackSize = 10;342        EntityRef toInventory = inventory;343        InventoryComponent toInventoryComp = toInventory.getComponent(InventoryComponent.class);344        EntityRef itemA1 = createItem("A", 8, stackSize);345        EntityRef itemB1 = createItem("B", 8, stackSize);346        EntityRef itemA2 = createItem("A", 7, stackSize);347        toInventoryComp.itemSlots.set(0, itemA1);348        toInventoryComp.itemSlots.set(2, itemB1);349        toInventoryComp.itemSlots.set(3, itemA2);350        EntityRef fromInventory = Mockito.mock(EntityRef.class);351        InventoryComponent fromInventoryComp = new InventoryComponent(5);352        Mockito.when(fromInventory.getComponent(InventoryComponent.class)).thenReturn(fromInventoryComp);353        EntityRef itemA3 = createItem("A", 4, stackSize);354        int fromSlot = 1;355        fromInventoryComp.itemSlots.set(fromSlot, itemA3);356        List<Integer> toSlots = Arrays.asList(0, 1, 2, 3, 4);357        // The method that gets tested:358        inventoryAuthoritySystem.moveItemToSlots(instigator, fromInventory, fromSlot, toInventory, toSlots);359        assertEquals(10, itemA1.getComponent(ItemComponent.class).stackCount);360        assertEquals(9, itemA2.getComponent(ItemComponent.class).stackCount);361        assertFalse(fromInventoryComp.itemSlots.get(fromSlot).exists());362    }363    @Test364    public void testMoveItemToSlotsWithSplittingToMultipleStacksAndEmptySlot() {365        int stackSize = 10;366        EntityRef toInventory = inventory;367        InventoryComponent toInventoryComp = toInventory.getComponent(InventoryComponent.class);368        EntityRef itemA1 = createItem("A", 8, stackSize);369        EntityRef itemB1 = createItem("B", 8, stackSize);370        EntityRef itemA2 = createItem("A", 7, stackSize);371        toInventoryComp.itemSlots.set(0, itemA1);372        toInventoryComp.itemSlots.set(2, itemB1);373        toInventoryComp.itemSlots.set(3, itemA2);374        EntityRef fromInventory = Mockito.mock(EntityRef.class);375        InventoryComponent fromInventoryComp = new InventoryComponent(5);376        Mockito.when(fromInventory.getComponent(InventoryComponent.class)).thenReturn(fromInventoryComp);377        EntityRef itemA3 = createItem("A", 8, stackSize);378        int fromSlot = 1;379        fromInventoryComp.itemSlots.set(fromSlot, itemA3);380        List<Integer> toSlots = Arrays.asList(0, 1, 2, 3, 4);381        // The method that gets tested:382        inventoryAuthoritySystem.moveItemToSlots(instigator, fromInventory, fromSlot, toInventory, toSlots);383        assertEquals(10, itemA1.getComponent(ItemComponent.class).stackCount);384        assertEquals(10, itemA2.getComponent(ItemComponent.class).stackCount);385        assertEquals(3, itemA3.getComponent(ItemComponent.class).stackCount);386        assertEquals(itemA3, toInventoryComp.itemSlots.get(1));387        assertFalse(fromInventoryComp.itemSlots.get(fromSlot).exists());388    }389    @Test390    public void testMoveItemToSlotsWithToLessSpaceInTargetSlots() {391        int stackSize = 10;392        EntityRef toInventory = inventory;393        InventoryComponent toInventoryComp = toInventory.getComponent(InventoryComponent.class);394        EntityRef itemA1 = createItem("A", 8, stackSize);395        EntityRef itemB1 = createItem("B", 8, stackSize);396        EntityRef itemA2 = createItem("A", 7, stackSize);397        toInventoryComp.itemSlots.set(0, itemA1);398        toInventoryComp.itemSlots.set(2, itemB1);399        toInventoryComp.itemSlots.set(3, itemA2);400        EntityRef fromInventory = Mockito.mock(EntityRef.class);401        InventoryComponent fromInventoryComp = new InventoryComponent(5);402        Mockito.when(fromInventory.getComponent(InventoryComponent.class)).thenReturn(fromInventoryComp);403        EntityRef itemA3 = createItem("A", 4, stackSize);404        int fromSlot = 1;405        fromInventoryComp.itemSlots.set(fromSlot, itemA3);406        List<Integer> toSlots = Arrays.asList(0, 2);407        // The method that gets tested:408        boolean result = inventoryAuthoritySystem.moveItemToSlots(instigator, fromInventory, fromSlot, toInventory, toSlots);409        assertTrue(result);410        assertEquals(10, itemA1.getComponent(ItemComponent.class).stackCount);411        assertEquals(7, itemA2.getComponent(ItemComponent.class).stackCount);412        assertEquals(2, itemA3.getComponent(ItemComponent.class).stackCount);413        assertEquals(itemA3, fromInventoryComp.itemSlots.get(fromSlot));414    }415    @Test416    public void testMoveItemToSlotsWithTargetVetos() {417        int stackSize = 10;418        EntityRef toInventory = inventory;419        InventoryComponent toInventoryComp = toInventory.getComponent(InventoryComponent.class);420        EntityRef itemA1 = createItem("A", 8, stackSize);421        toInventoryComp.itemSlots.set(0, itemA1);422        EntityRef fromInventory = Mockito.mock(EntityRef.class);423        InventoryComponent fromInventoryComp = new InventoryComponent(5);424        Mockito.when(fromInventory.getComponent(InventoryComponent.class)).thenReturn(fromInventoryComp);425        EntityRef itemA2 = createItem("A", 5, stackSize);426        int fromSlot = 1;427        fromInventoryComp.itemSlots.set(fromSlot, itemA2);428        // Placement to slots 1 gets blocked by veto429        Mockito.when(inventory.send(Matchers.any(BeforeItemPutInInventory.class))).then(430                invocation -> {431                    Object arg = invocation.getArguments()[0];432                    if (arg instanceof BeforeItemPutInInventory) {433                        BeforeItemPutInInventory event = (BeforeItemPutInInventory) arg;434                        if (event.getSlot() == 1) {435                            event.consume();436                        }437                    }438                    return null;439                }440        );441        List<Integer> toSlots = Arrays.asList(0, 1, 2, 3, 4);442        // The method that gets tested:443        boolean result = inventoryAuthoritySystem.moveItemToSlots(instigator, fromInventory, fromSlot, toInventory, toSlots);444        assertTrue(result);445        /*446         * The free slot 1 can't be used since it's blocked:447         * => A1 gets still filled up and the rest of the items gets placed at slot 2448         */449        assertEquals(10, itemA1.getComponent(ItemComponent.class).stackCount);450        assertEquals(3, itemA2.getComponent(ItemComponent.class).stackCount);451        assertEquals(EntityRef.NULL, toInventoryComp.itemSlots.get(1));452        assertEquals(itemA2, toInventoryComp.itemSlots.get(2));453        assertFalse(fromInventoryComp.itemSlots.get(fromSlot).exists());454    }455    /**456     * A shift click isn't possible because the removal of the item gets blocked457     */458    @Test459    public void testMoveItemToSlotsWithRemovalVeto() {460        int stackSize = 10;461        EntityRef toInventory = inventory;462        InventoryComponent toInventoryComp = toInventory.getComponent(InventoryComponent.class);463        EntityRef itemA1 = createItem("A", 8, stackSize);464        toInventoryComp.itemSlots.set(0, itemA1);465        EntityRef fromInventory = Mockito.mock(EntityRef.class);466        InventoryComponent fromInventoryComp = new InventoryComponent(5);467        Mockito.when(fromInventory.getComponent(InventoryComponent.class)).thenReturn(fromInventoryComp);468        EntityRef itemA2 = createItem("A", 5, stackSize);469        int fromSlot = 1;470        fromInventoryComp.itemSlots.set(fromSlot, itemA2);471        // Placement to slots 1 gets blocked by veto472        Mockito.when(fromInventory.send(Matchers.any(BeforeItemRemovedFromInventory.class))).then(473                invocation -> {474                    Object arg = invocation.getArguments()[0];475                    if (arg instanceof BeforeItemRemovedFromInventory) {476                        BeforeItemRemovedFromInventory event = (BeforeItemRemovedFromInventory) arg;477                        if (event.getSlot() == 1) {478                            event.consume();479                        }480                    }481                    return null;482                }483        );484        List<Integer> toSlots = Arrays.asList(0, 1, 2, 3, 4);485        // The method that gets tested:486        boolean result = inventoryAuthoritySystem.moveItemToSlots(instigator, fromInventory, fromSlot, toInventory, toSlots);487        assertFalse(result);488        assertEquals(8, itemA1.getComponent(ItemComponent.class).stackCount);489        assertEquals(5, itemA2.getComponent(ItemComponent.class).stackCount);490        assertEquals(EntityRef.NULL, toInventoryComp.itemSlots.get(1));491        assertEquals(itemA2, fromInventoryComp.itemSlots.get(fromSlot));492    }493    @Test494    public void testMoveItemToSlotsWithFullTargetInventorySlots() {495        int stackSize = 10;496        EntityRef toInventory = inventory;497        InventoryComponent toInventoryComp = toInventory.getComponent(InventoryComponent.class);498        EntityRef itemA1 = createItem("A", 10, stackSize);499        EntityRef itemB1 = createItem("B", 8, stackSize);500        EntityRef itemA2 = createItem("A", 10, stackSize);501        toInventoryComp.itemSlots.set(0, itemA1);502        toInventoryComp.itemSlots.set(1, itemB1);503        toInventoryComp.itemSlots.set(2, itemA2);504        EntityRef fromInventory = Mockito.mock(EntityRef.class);505        InventoryComponent fromInventoryComp = new InventoryComponent(5);506        Mockito.when(fromInventory.getComponent(InventoryComponent.class)).thenReturn(fromInventoryComp);507        EntityRef itemA3 = createItem("A", 4, stackSize);508        int fromSlot = 1;509        fromInventoryComp.itemSlots.set(fromSlot, itemA3);510        List<Integer> toSlots = Arrays.asList(0, 1, 2);511        // The method that gets tested:512        boolean result = inventoryAuthoritySystem.moveItemToSlots(instigator, fromInventory, fromSlot, toInventory, toSlots);513        assertFalse(result);514        assertEquals(10, itemA1.getComponent(ItemComponent.class).stackCount);515        assertEquals(10, itemA2.getComponent(ItemComponent.class).stackCount);516        assertEquals(4, itemA3.getComponent(ItemComponent.class).stackCount);517        assertEquals(itemA3, fromInventoryComp.itemSlots.get(fromSlot));518    }519}...Source:TestHBaseAdminNoCluster.java  
...99      } catch (RetriesExhaustedException e) {100        LOG.info("Expected fail", e);101      }102      // Assert we were called 'count' times.103      Mockito.verify(masterAdmin, Mockito.atLeast(count)).createTable((RpcController)Mockito.any(),104        (CreateTableRequest)Mockito.any());105    } finally {106      admin.close();107      if (connection != null) connection.close();108    }109  }110  @Test111  public void testMasterOperationsRetries() throws Exception {112    // Admin.listTables()113    testMasterOperationIsRetried(new MethodCaller() {114      @Override115      public void call(Admin admin) throws Exception {116        admin.listTables();117      }118      @Override119      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {120        Mockito.verify(masterAdmin, Mockito.atLeast(count))121          .getTableDescriptors((RpcController)Mockito.any(),122            (GetTableDescriptorsRequest)Mockito.any());123      }124    });125    // Admin.listTableNames()126    testMasterOperationIsRetried(new MethodCaller() {127      @Override128      public void call(Admin admin) throws Exception {129        admin.listTableNames();130      }131      @Override132      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {133        Mockito.verify(masterAdmin, Mockito.atLeast(count))134          .getTableNames((RpcController)Mockito.any(),135            (GetTableNamesRequest)Mockito.any());136      }137    });138    // Admin.getTableDescriptor()139    testMasterOperationIsRetried(new MethodCaller() {140      @Override141      public void call(Admin admin) throws Exception {142        admin.getTableDescriptor(TableName.valueOf("getTableDescriptor"));143      }144      @Override145      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {146        Mockito.verify(masterAdmin, Mockito.atLeast(count))147          .getTableDescriptors((RpcController)Mockito.any(),148            (GetTableDescriptorsRequest)Mockito.any());149      }150    });151    // Admin.getTableDescriptorsByTableName()152    testMasterOperationIsRetried(new MethodCaller() {153      @Override154      public void call(Admin admin) throws Exception {155        admin.getTableDescriptorsByTableName(new ArrayList<TableName>());156      }157      @Override158      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {159        Mockito.verify(masterAdmin, Mockito.atLeast(count))160          .getTableDescriptors((RpcController)Mockito.any(),161            (GetTableDescriptorsRequest)Mockito.any());162      }163    });164    // Admin.move()165    testMasterOperationIsRetried(new MethodCaller() {166      @Override167      public void call(Admin admin) throws Exception {168        admin.move(new byte[0], null);169      }170      @Override171      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {172        Mockito.verify(masterAdmin, Mockito.atLeast(count))173          .moveRegion((RpcController)Mockito.any(),174            (MoveRegionRequest)Mockito.any());175      }176    });177    // Admin.offline()178    testMasterOperationIsRetried(new MethodCaller() {179      @Override180      public void call(Admin admin) throws Exception {181        admin.offline(new byte[0]);182      }183      @Override184      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {185        Mockito.verify(masterAdmin, Mockito.atLeast(count))186          .offlineRegion((RpcController)Mockito.any(),187            (OfflineRegionRequest)Mockito.any());188      }189    });190    // Admin.setBalancerRunning()191    testMasterOperationIsRetried(new MethodCaller() {192      @Override193      public void call(Admin admin) throws Exception {194        admin.setBalancerRunning(true, true);195      }196      @Override197      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {198        Mockito.verify(masterAdmin, Mockito.atLeast(count))199          .setBalancerRunning((RpcController)Mockito.any(),200            (SetBalancerRunningRequest)Mockito.any());201      }202    });203    // Admin.balancer()204    testMasterOperationIsRetried(new MethodCaller() {205      @Override206      public void call(Admin admin) throws Exception {207        admin.balancer();208      }209      @Override210      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {211        Mockito.verify(masterAdmin, Mockito.atLeast(count))212          .balance((RpcController)Mockito.any(),213            (BalanceRequest)Mockito.any());214      }215    });216    // Admin.enabledCatalogJanitor()217    testMasterOperationIsRetried(new MethodCaller() {218      @Override219      public void call(Admin admin) throws Exception {220        admin.enableCatalogJanitor(true);221      }222      @Override223      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {224        Mockito.verify(masterAdmin, Mockito.atLeast(count))225          .enableCatalogJanitor((RpcController)Mockito.any(),226            (EnableCatalogJanitorRequest)Mockito.any());227      }228    });229    // Admin.runCatalogScan()230    testMasterOperationIsRetried(new MethodCaller() {231      @Override232      public void call(Admin admin) throws Exception {233        admin.runCatalogScan();234      }235      @Override236      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {237        Mockito.verify(masterAdmin, Mockito.atLeast(count))238          .runCatalogScan((RpcController)Mockito.any(),239            (RunCatalogScanRequest)Mockito.any());240      }241    });242    // Admin.isCatalogJanitorEnabled()243    testMasterOperationIsRetried(new MethodCaller() {244      @Override245      public void call(Admin admin) throws Exception {246        admin.isCatalogJanitorEnabled();247      }248      @Override249      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {250        Mockito.verify(masterAdmin, Mockito.atLeast(count))251          .isCatalogJanitorEnabled((RpcController)Mockito.any(),252            (IsCatalogJanitorEnabledRequest)Mockito.any());253      }254    });255    // Admin.mergeRegions()256    testMasterOperationIsRetried(new MethodCaller() {257      @Override258      public void call(Admin admin) throws Exception {259        admin.mergeRegions(new byte[0], new byte[0], true);260      }261      @Override262      public void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception {263        Mockito.verify(masterAdmin, Mockito.atLeast(count))264          .dispatchMergingRegions((RpcController)Mockito.any(),265            (DispatchMergingRegionsRequest)Mockito.any());266      }267    });268  }269  private static interface MethodCaller {270    void call(Admin admin) throws Exception;271    void verify(MasterKeepAliveConnection masterAdmin, int count) throws Exception;272  }273  private void testMasterOperationIsRetried(MethodCaller caller) throws Exception {274    Configuration configuration = HBaseConfiguration.create();275    // Set the pause and retry count way down.276    configuration.setLong(HConstants.HBASE_CLIENT_PAUSE, 1);277    final int count = 10;...Source:TrackingKnowledgeContainerTest.java  
...3import static org.junit.Assert.assertFalse;4import static org.junit.Assert.assertTrue;5import static org.mockito.Matchers.any;6import static org.mockito.Matchers.eq;7import static org.mockito.Mockito.atLeast;8import static org.mockito.Mockito.atMost;9import static org.mockito.Mockito.eq;10import static org.mockito.Mockito.refEq;11import static org.mockito.Mockito.spy;12import static org.mockito.Mockito.times;1314import java.util.ArrayList;15import java.util.Arrays;16import java.util.Collection;17import java.util.List;1819import org.junit.Test;20import org.mockito.Mockito;2122public class TrackingKnowledgeContainerTest {2324	@Test25	public void getUntrackedKnowledgeEmptyShadowTest() throws KnowledgeContainerException, RoleClassException, KnowledgeAccessException {26		TrackingKnowledgeWrapper localWrapperMock = Mockito.mock(TrackingKnowledgeWrapper.class);27		List<ReadOnlyKnowledgeWrapper> shadowWrapperMocks = new ArrayList<ReadOnlyKnowledgeWrapper>();28		Mockito.when(localWrapperMock.hasRole(eq(String.class))).thenReturn(true);29		Mockito.when(localWrapperMock.getUntrackedRoleKnowledge(eq(String.class))).thenReturn("S0");30		31		TrackingKnowledgeContainer target = new TrackingKnowledgeContainer(localWrapperMock, shadowWrapperMocks);32		Collection<String> result = target.getUntrackedKnowledgeForRole(String.class);33		34		assertTrue(result.size() == 1);35		assertTrue(result.contains("S0"));36		Mockito.verify(localWrapperMock, atLeast(1)).hasRole(eq(String.class));37		Mockito.verify(localWrapperMock, times(1)).getUntrackedRoleKnowledge(eq(String.class));38		Mockito.verifyNoMoreInteractions(localWrapperMock);39	}40	41	@Test42	public void getUntrackedKnowledgeEmptyResultTest() throws RoleClassException, KnowledgeAccessException, KnowledgeContainerException {43		TrackingKnowledgeWrapper localWrapperMock = Mockito.mock(TrackingKnowledgeWrapper.class);44		List<ReadOnlyKnowledgeWrapper> shadowWrapperMocks = Arrays.asList(45				Mockito.mock(ReadOnlyKnowledgeWrapper.class), Mockito.mock(ReadOnlyKnowledgeWrapper.class)46				);47		Mockito.when(localWrapperMock.hasRole(eq(String.class))).thenReturn(false);48		Mockito.when(shadowWrapperMocks.get(0).hasRole(eq(String.class))).thenReturn(false);49		Mockito.when(shadowWrapperMocks.get(1).hasRole(eq(String.class))).thenReturn(false);50		51		TrackingKnowledgeContainer target = new TrackingKnowledgeContainer(localWrapperMock, shadowWrapperMocks);52		Collection<String> result = target.getUntrackedKnowledgeForRole(String.class);53		54		assertTrue(result.size() == 0);55		56		Mockito.verify(localWrapperMock, atLeast(1)).hasRole(eq(String.class));57		Mockito.verify(shadowWrapperMocks.get(0), atLeast(1)).hasRole(eq(String.class));58		Mockito.verify(shadowWrapperMocks.get(1), atLeast(1)).hasRole(eq(String.class));59		Mockito.verifyNoMoreInteractions(localWrapperMock, shadowWrapperMocks.get(0), shadowWrapperMocks.get(1));6061	}62	63	@Test64	public void getUntrackedKnowledgeTest() throws KnowledgeContainerException, RoleClassException, KnowledgeAccessException {65		TrackingKnowledgeWrapper localWrapperMock = Mockito.mock(TrackingKnowledgeWrapper.class);66		List<ReadOnlyKnowledgeWrapper> shadowWrapperMocks = Arrays.asList(67				Mockito.mock(ReadOnlyKnowledgeWrapper.class), Mockito.mock(ReadOnlyKnowledgeWrapper.class), Mockito.mock(ReadOnlyKnowledgeWrapper.class)68				);69		Mockito.when(localWrapperMock.hasRole(eq(String.class))).thenReturn(true);70		Mockito.when(localWrapperMock.getUntrackedRoleKnowledge(eq(String.class))).thenReturn("S0");71		Mockito.when(shadowWrapperMocks.get(0).hasRole(eq(String.class))).thenReturn(true);72		Mockito.when(shadowWrapperMocks.get(0).getUntrackedRoleKnowledge(eq(String.class))).thenReturn("S1");73		Mockito.when(shadowWrapperMocks.get(1).hasRole(eq(String.class))).thenReturn(false);74		Mockito.when(shadowWrapperMocks.get(2).hasRole(eq(String.class))).thenReturn(true);75		Mockito.when(shadowWrapperMocks.get(2).getUntrackedRoleKnowledge(eq(String.class))).thenReturn("S2");76		77		TrackingKnowledgeContainer target = new TrackingKnowledgeContainer(localWrapperMock, shadowWrapperMocks);78		Collection<String> result = target.getUntrackedKnowledgeForRole(String.class);79		80		assertTrue(result.size() == 3);81		assertTrue(result.contains("S0"));82		assertTrue(result.contains("S1"));83		assertTrue(result.contains("S2"));84		85		Mockito.verify(localWrapperMock, atLeast(1)).hasRole(eq(String.class));86		Mockito.verify(shadowWrapperMocks.get(0), atLeast(1)).hasRole(eq(String.class));87		Mockito.verify(shadowWrapperMocks.get(1), atLeast(1)).hasRole(eq(String.class));88		Mockito.verify(shadowWrapperMocks.get(2), atLeast(1)).hasRole(eq(String.class));89		Mockito.verify(localWrapperMock, times(1)).getUntrackedRoleKnowledge(eq(String.class));90		Mockito.verify(shadowWrapperMocks.get(0), times(1)).getUntrackedRoleKnowledge(eq(String.class));91		Mockito.verify(shadowWrapperMocks.get(2), times(1)).getUntrackedRoleKnowledge(eq(String.class));92		Mockito.verifyNoMoreInteractions(localWrapperMock, shadowWrapperMocks.get(0), shadowWrapperMocks.get(1), shadowWrapperMocks.get(2));93	}9495	@Test96	// variant of getUntrackedKnowledgeEmptyShadowTest using tracking97	public void getTrackedKnowledgeEmptyShadowTest() throws KnowledgeContainerException, RoleClassException, KnowledgeAccessException {98		TrackingKnowledgeWrapper localWrapperMock = Mockito.mock(TrackingKnowledgeWrapper.class);99		List<ReadOnlyKnowledgeWrapper> shadowWrapperMocks = new ArrayList<ReadOnlyKnowledgeWrapper>();100		Mockito.when(localWrapperMock.hasRole(eq(String.class))).thenReturn(true);101		Mockito.when(localWrapperMock.getTrackedRoleKnowledge(eq(String.class))).thenReturn("S0");102		103		TrackingKnowledgeContainer target = new TrackingKnowledgeContainer(localWrapperMock, shadowWrapperMocks);104		Collection<String> result = target.getTrackedKnowledgeForRole(String.class);105		106		assertTrue(result.size() == 1);107		assertTrue(result.contains("S0"));108		Mockito.verify(localWrapperMock, atLeast(1)).hasRole(eq(String.class));109		Mockito.verify(localWrapperMock, times(1)).getTrackedRoleKnowledge(eq(String.class));110		Mockito.verifyNoMoreInteractions(localWrapperMock);111	}112	113	@Test114	// variant of getUntrackedKnowledgeEmptyResultTest using tracking115	public void getTrackedKnowledgeEmptyResultTest() throws RoleClassException, KnowledgeAccessException, KnowledgeContainerException {116		TrackingKnowledgeWrapper localWrapperMock = Mockito.mock(TrackingKnowledgeWrapper.class);117		List<ReadOnlyKnowledgeWrapper> shadowWrapperMocks = Arrays.asList(118				Mockito.mock(ReadOnlyKnowledgeWrapper.class), Mockito.mock(ReadOnlyKnowledgeWrapper.class)119				);120		Mockito.when(localWrapperMock.hasRole(eq(String.class))).thenReturn(false);121		Mockito.when(shadowWrapperMocks.get(0).hasRole(eq(String.class))).thenReturn(false);122		Mockito.when(shadowWrapperMocks.get(1).hasRole(eq(String.class))).thenReturn(false);123		124		TrackingKnowledgeContainer target = new TrackingKnowledgeContainer(localWrapperMock, shadowWrapperMocks);125		Collection<String> result = target.getTrackedKnowledgeForRole(String.class);126		127		assertTrue(result.size() == 0);128		129		Mockito.verify(localWrapperMock, atLeast(1)).hasRole(eq(String.class));130		Mockito.verify(shadowWrapperMocks.get(0), atLeast(1)).hasRole(eq(String.class));131		Mockito.verify(shadowWrapperMocks.get(1), atLeast(1)).hasRole(eq(String.class));132		Mockito.verifyNoMoreInteractions(localWrapperMock, shadowWrapperMocks.get(0), shadowWrapperMocks.get(1));133134	}135	136	@Test137	// variant of getUntrackedKnowledgeTest using tracking138	public void getTrackedKnowledgeTest() throws KnowledgeContainerException, RoleClassException, KnowledgeAccessException {139		TrackingKnowledgeWrapper localWrapperMock = Mockito.mock(TrackingKnowledgeWrapper.class);140		List<ReadOnlyKnowledgeWrapper> shadowWrapperMocks = Arrays.asList(141				Mockito.mock(ReadOnlyKnowledgeWrapper.class), Mockito.mock(ReadOnlyKnowledgeWrapper.class), Mockito.mock(ReadOnlyKnowledgeWrapper.class)142				);143		Mockito.when(localWrapperMock.hasRole(eq(String.class))).thenReturn(true);144		Mockito.when(localWrapperMock.getTrackedRoleKnowledge(eq(String.class))).thenReturn("S0");145		Mockito.when(shadowWrapperMocks.get(0).hasRole(eq(String.class))).thenReturn(true);146		Mockito.when(shadowWrapperMocks.get(0).getUntrackedRoleKnowledge(eq(String.class))).thenReturn("S1");147		Mockito.when(shadowWrapperMocks.get(1).hasRole(eq(String.class))).thenReturn(false);148		Mockito.when(shadowWrapperMocks.get(2).hasRole(eq(String.class))).thenReturn(true);149		Mockito.when(shadowWrapperMocks.get(2).getUntrackedRoleKnowledge(eq(String.class))).thenReturn("S2");150		151		TrackingKnowledgeContainer target = new TrackingKnowledgeContainer(localWrapperMock, shadowWrapperMocks);152		Collection<String> result = target.getTrackedKnowledgeForRole(String.class);153		154		assertTrue(result.size() == 3);155		assertTrue(result.contains("S0"));156		assertTrue(result.contains("S1"));157		assertTrue(result.contains("S2"));158		159		Mockito.verify(localWrapperMock, atLeast(1)).hasRole(eq(String.class));160		Mockito.verify(shadowWrapperMocks.get(0), atLeast(1)).hasRole(eq(String.class));161		Mockito.verify(shadowWrapperMocks.get(1), atLeast(1)).hasRole(eq(String.class));162		Mockito.verify(shadowWrapperMocks.get(2), atLeast(1)).hasRole(eq(String.class));163		Mockito.verify(localWrapperMock, times(1)).getTrackedRoleKnowledge(eq(String.class));164		Mockito.verify(shadowWrapperMocks.get(0), times(1)).getUntrackedRoleKnowledge(eq(String.class));165		Mockito.verify(shadowWrapperMocks.get(2), times(1)).getUntrackedRoleKnowledge(eq(String.class));166		Mockito.verifyNoMoreInteractions(localWrapperMock, shadowWrapperMocks.get(0), shadowWrapperMocks.get(1), shadowWrapperMocks.get(2));167	}168	169	@Test170	public void commitChangesTest() throws KnowledgeContainerException, KnowledgeCommitException, KnowledgeAccessException, RoleClassException {171		TrackingKnowledgeWrapper localWrapperMock = Mockito.mock(TrackingKnowledgeWrapper.class);172		List<ReadOnlyKnowledgeWrapper> shadowWrapperMocks = Arrays.asList(173				Mockito.mock(ReadOnlyKnowledgeWrapper.class), Mockito.mock(ReadOnlyKnowledgeWrapper.class)174				);175		176		TrackingKnowledgeContainer target = new TrackingKnowledgeContainer(localWrapperMock, shadowWrapperMocks);
...Source:LoggingActivatorTest.java  
...71    public void testOverrideLoggerLevels_loggerNotAvailable_logWarning() {72        PowerMockito.when(loggerContext.getLogger(ArgumentMatchers.anyString())).thenReturn(null);73        Mockito.mock(LoggerContext.class);74        activator.overrideLoggerLevels(loggerContext);75        Mockito.verify(loggerContext, Mockito.atLeast(1)).getLogger(ArgumentMatchers.anyString());76        Mockito.verify(activatorLogger, Mockito.atLeast(1)).warn(ArgumentMatchers.anyString(), ArgumentMatchers.anyString());77    }78    @Test79    public void testOverrideLoggerLevels_configuredLevelWARNTooCoarse_setNewLogLevel() {80        Mockito.when(logger.getLevel()).thenReturn(Level.WARN);81        activator.overrideLoggerLevels(loggerContext);82        Mockito.verify(logger, Mockito.atLeast(1)).setLevel(Level.INFO);83        Mockito.verify(loggerContext, Mockito.atLeast(1)).getLogger(ArgumentMatchers.anyString());84        Mockito.verify(activatorLogger, Mockito.never()).warn(ArgumentMatchers.anyString());85    }86    @Test87    public void testOverrideLoggerLevels_configuredLevelNull_setNewLogLevel() {88        Mockito.when(logger.getLevel()).thenReturn(null);89        activator.overrideLoggerLevels(loggerContext);90        Mockito.verify(logger, Mockito.atLeast(1)).setLevel(Level.INFO);91        Mockito.verify(loggerContext, Mockito.atLeast(1)).getLogger(ArgumentMatchers.anyString());92        Mockito.verify(activatorLogger, Mockito.never()).warn(ArgumentMatchers.anyString());93    }94    @Test95    public void testOverrideLoggerLevels_configuredLevelOFFTooCoarse_setNewLogLevel() {96        Mockito.when(logger.getLevel()).thenReturn(Level.OFF);97        activator.overrideLoggerLevels(loggerContext);98        Mockito.verify(logger, Mockito.atLeast(1)).setLevel(Level.INFO);99        Mockito.verify(loggerContext, Mockito.atLeast(1)).getLogger(ArgumentMatchers.anyString());100        Mockito.verify(activatorLogger, Mockito.never()).warn(ArgumentMatchers.anyString());101    }102    @Test103    public void testOverrideLoggerLevels_configuredLevelINFOAdequate_doNotSetNewLogLevel() {104        Mockito.when(logger.getLevel()).thenReturn(Level.INFO);105        activator.overrideLoggerLevels(loggerContext);106        Mockito.verify(logger, Mockito.never()).setLevel(Level.INFO);107        Mockito.verify(loggerContext, Mockito.atLeast(1)).getLogger(ArgumentMatchers.anyString());108        Mockito.verify(activatorLogger, Mockito.never()).warn(ArgumentMatchers.anyString());109    }110    @Test111    public void testOverrideLoggerLevels_configuredLevelALLAdequate_doNotSetNewLogLevel() {112        Mockito.when(logger.getLevel()).thenReturn(Level.ALL);113        activator.overrideLoggerLevels(loggerContext);114        Mockito.verify(logger, Mockito.never()).setLevel(Level.INFO);115        Mockito.verify(loggerContext, Mockito.atLeast(1)).getLogger(ArgumentMatchers.anyString());116        Mockito.verify(activatorLogger, Mockito.never()).warn(ArgumentMatchers.anyString());117    }118    @Test119    public void testOverrideLoggerLevels_disableOverrideLogLevels_returnWithOverriding() {120        Mockito.when(logger.getLevel()).thenReturn(Level.OFF);121        PowerMockito.when(loggerContext.getProperty(ArgumentMatchers.anyString())).thenReturn("true");122        activator.overrideLoggerLevels(loggerContext);123        Mockito.verify(logger, Mockito.never()).setLevel(Level.INFO);124        Mockito.verify(loggerContext, Mockito.never()).getLogger(ArgumentMatchers.anyString());125        Mockito.verify(activatorLogger, Mockito.never()).warn(ArgumentMatchers.anyString());126    }127    @Test128    public void testStartBundle_ensureOverrideLoggerLevelsCalled_successfull() throws Exception {129        BundleContext bundleContext = PowerMockito.mock(BundleContext.class);130        Bundle bundle = PowerMockito.mock(Bundle.class);131        Mockito.when(bundleContext.getBundle()).thenReturn(bundle);132        PowerMockito.when(loggerContext.getTurboFilterList()).thenReturn(new TurboFilterList());133        LoggingActivator activatorSpy = Mockito.spy(activator);134        Mockito.doNothing().when(activatorSpy).overrideLoggerLevels(loggerContext);135        Mockito.doNothing().when(activatorSpy).configureJavaUtilLogging();136        Mockito.doNothing().when(activatorSpy).installJulLevelChangePropagator(loggerContext);137        Mockito.doNothing().when(activatorSpy).registerDeprecatedLogstashAppenderMBeanTracker(ArgumentMatchers.eq(bundleContext));138        activatorSpy.start(bundleContext);139        Mockito.verify(activatorSpy, Mockito.times(1)).overrideLoggerLevels(loggerContext);140    }141    @Test142    public void testStartBundle_ensureInstallJulLevelChangePropagatorCalled_successfull() throws Exception {143        BundleContext bundleContext = PowerMockito.mock(BundleContext.class);144        Bundle bundle = PowerMockito.mock(Bundle.class);145        Mockito.when(bundleContext.getBundle()).thenReturn(bundle);146        PowerMockito.when(loggerContext.getTurboFilterList()).thenReturn(new TurboFilterList());147        LoggingActivator activatorSpy = Mockito.spy(activator);148        Mockito.doNothing().when(activatorSpy).overrideLoggerLevels(loggerContext);149        Mockito.doNothing().when(activatorSpy).configureJavaUtilLogging();150        Mockito.doNothing().when(activatorSpy).installJulLevelChangePropagator(loggerContext);151        Mockito.doNothing().when(activatorSpy).registerDeprecatedLogstashAppenderMBeanTracker(ArgumentMatchers.eq(bundleContext));152        activatorSpy.start(bundleContext);153        Mockito.verify(activatorSpy, Mockito.times(1)).installJulLevelChangePropagator(loggerContext);154    }155    @Test156    public void testInstallJulLevelChangePropagator_propagatorNotAvailable_addPropagator() {157        LoggingActivator activatorSpy = Mockito.spy(activator);158        Mockito.doReturn(Boolean.FALSE).when(activatorSpy).hasInstanceOf(ArgumentMatchers.anyCollection(), ArgumentMatchers.any(Class.class));159        activatorSpy.installJulLevelChangePropagator(loggerContext);160        Mockito.verify(loggerContext, Mockito.atLeast(1)).addListener((LoggerContextListener) ArgumentMatchers.any());161    }162    @Test163    public void testInstallJulLevelChangePropagator_propagatorAvailable_DoNothing() {164        LoggingActivator activatorSpy = Mockito.spy(activator);165        Mockito.doReturn(Boolean.TRUE).when(activatorSpy).hasInstanceOf(ArgumentMatchers.anyCollection(), ArgumentMatchers.any(Class.class));166        activatorSpy.installJulLevelChangePropagator(loggerContext);167        Mockito.verify(loggerContext, Mockito.never()).addListener((LoggerContextListener) ArgumentMatchers.any());168    }169    @Test(expected = IllegalArgumentException.class)170    public void testInstallJulLevelChangePropagator_collectionNull_throwException() {171        activator.hasInstanceOf(null, LevelChangePropagator.class);172    }173    @Test174    public void testInstallJulLevelChangePropagator_classNullCollectionEmpty_returnFalse() {...Source:DroneBricksActionTests.java  
...81		action.act(actDuration);82	}83	public void testFlip() {84		addActionToSequenceAndAct(new DroneFlipBrick());85		Mockito.verify(droneControlService, Mockito.atLeast(1)).doLeftFlip();86	}87	public void testPlayLedAnimation() {88		addActionToSequenceAndAct(new DronePlayLedAnimationBrick());89		Mockito.verify(droneControlService, Mockito.atLeast(1)).playLedAnimation(5.0f, 3, 3);90	}91	public void testTakeOff() {92		addActionToSequenceAndAct(new DroneTakeOffLandBrick());93		Mockito.verify(droneControlService, Mockito.atLeast(1)).triggerTakeOff();94	}95	public void testLand() {96		addActionToSequenceAndAct(new DroneTakeOffLandBrick());97		Mockito.verify(droneControlService, Mockito.atLeast(1)).triggerTakeOff();98	}99	public void testMoveUp() {100		DroneMoveUpBrick moveUpBrick = new DroneMoveUpBrick(durationInSeconds, powerInPercent);101		addActionToSequenceAndAct(moveUpBrick, 2);102		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveUp(0.2f);103		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveUp(0);104	}105	public void testMoveDown() {106		DroneMoveDownBrick moveDownBrick = new DroneMoveDownBrick(durationInSeconds, powerInPercent);107		addActionToSequenceAndAct(moveDownBrick, 2);108		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveDown(0.2f);109		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveDown(0);110	}111	public void testMoveLeft() {112		DroneMoveLeftBrick moveLeftBrick = new DroneMoveLeftBrick(durationInSeconds, powerInPercent);113		addActionToSequenceAndAct(moveLeftBrick, 2);114		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveLeft(0.2f);115		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveLeft(0);116	}117	public void testMoveRight() {118		DroneMoveRightBrick moveRightBrick = new DroneMoveRightBrick(durationInSeconds, powerInPercent);119		addActionToSequenceAndAct(moveRightBrick, 2);120		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveRight(0.2f);121		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveRight(0);122	}123	public void testMoveForward() {124		DroneMoveForwardBrick moveForwardBrick = new DroneMoveForwardBrick(durationInSeconds, powerInPercent);125		addActionToSequenceAndAct(moveForwardBrick, 2);126		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveForward(0.2f);127		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveForward(0);128	}129	public void testMoveBackward() {130		DroneMoveBackwardBrick moveBackwardBrick = new DroneMoveBackwardBrick(durationInSeconds, powerInPercent);131		addActionToSequenceAndAct(moveBackwardBrick, 2);132		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveBackward(0.2f);133		Mockito.verify(droneControlService, Mockito.atLeast(1)).moveBackward(0);134	}135	public void testTurnLeft() {136		DroneTurnLeftBrick turnLeftBrick = new DroneTurnLeftBrick(durationInSeconds, powerInPercent);137		addActionToSequenceAndAct(turnLeftBrick, 2);138		Mockito.verify(droneControlService, Mockito.atLeast(1)).turnLeft(0.2f);139		Mockito.verify(droneControlService, Mockito.atLeast(1)).turnLeft(0);140	}141	public void testTurnRight() {142		DroneTurnRightBrick turnRightBrick = new DroneTurnRightBrick(durationInSeconds, powerInPercent);143		addActionToSequenceAndAct(turnRightBrick, 2);144		Mockito.verify(droneControlService, Mockito.atLeast(1)).turnRight(0.2f);145		Mockito.verify(droneControlService, Mockito.atLeast(1)).turnRight(0);146	}147//	public void testConfigBrickSpinnerPosition0() {148//		DroneSetConfigBrick configBrick = new DroneSetConfigBrick();149//		configBrick.setSpinnerPosition(0);150//		addActionToSequenceAndAct(configBrick);151//		Mockito.verify(droneControlService, Mockito.atLeast(1)).resetConfigToDefaults();152//	}153//154//	public void testConfigBrickSpinnerPosition1() {155//		DroneSetConfigBrick configBrick = new DroneSetConfigBrick();156//		configBrick.setSpinnerPosition(1);157//		addActionToSequenceAndAct(configBrick);158//		Mockito.verify(droneConfig, Mockito.atLeast(1)).setOutdoorFlight(false);159//	}160//161//	public void testConfigBrickSpinnerPosition2() {162//		DroneSetConfigBrick configBrick = new DroneSetConfigBrick();163//		configBrick.setSpinnerPosition(2);164//		addActionToSequenceAndAct(configBrick);165//		Mockito.verify(droneConfig, Mockito.atLeast(1)).setOutdoorFlight(true);166//	}167	public void testSwitch() {168		DroneSwitchCameraBrick switchBrick = new DroneSwitchCameraBrick();169		addActionToSequenceAndAct(switchBrick);170		Mockito.verify(droneControlService, Mockito.atLeast(1)).switchCamera();171	}172}...Source:RunMojoTest.java  
...43    //        RunMojo mojo = new SubRunMojo(bootstrap);44    //        mojo.catalinaBase = catalinaBaseDir;45    //        mojo.tomcatSetAwait = false;46    //        mojo.execute();47    //        Mockito.verify(bootstrap, Mockito.atLeastOnce()).start();48    //        Assert.assertEquals(bootstrap, mojo.getPluginContext().get(AbstractT7BaseMojo.T7_BOOTSTRAP_CONTEXT_ID));49    //    }50    //51    //    @Test(expected = MojoExecutionException.class)52    //    public void testRunMojoSetAwaitWithException() throws Exception {53    //        RunMojo mojo = new SubRunMojo(bootstrap);54    //        mojo.catalinaBase = catalinaBaseDir;55    //        mojo.tomcatSetAwait = true;56    //57    //        Mockito.doThrow(new Exception("TESTEXCEPTION")).when(bootstrap).start();58    //59    //        mojo.execute();60    ////        Mockito.verify(Mockito.atLeast(1)).buildTomcat();61    //        Mockito.verify(bootstrap, Mockito.atLeast(1)).init();62    //        Mockito.verify(bootstrap, Mockito.atLeast(1)).setAwait(Mockito.anyBoolean());63    //        Mockito.verify(bootstrap, Mockito.atLeast(1)).start();64    //    }65    //66    //    @Test67    //    public void testRunMojoSetAwait() throws Exception {68    //        RunMojo mojo = new SubRunMojo(bootstrap);69    //        mojo.catalinaBase = catalinaBaseDir;70    //        mojo.tomcatSetAwait = true;71    //        mojo.execute();72    //        Mockito.verify(bootstrap, Mockito.atLeast(1)).init();73    //        Mockito.verify(bootstrap, Mockito.atLeast(1)).setAwait(Mockito.anyBoolean());74    //        Mockito.verify(bootstrap, Mockito.atLeast(1)).start();75    //    }76    //    @Test77    //    public void testGetTomcatSetup() {78    //        RunMojo mojo = new RunMojo();79    //        Bootstrap bootstrap = mojo.getBootstrap();80    //        Assert.assertNotNull(bootstrap);81    //        Assert.assertEquals(Bootstrap.class, bootstrap.getClass());82    //        TomcatSetup setup = mojo.getTomcatSetup();83    //        Assert.assertNotNull(setup);84    //        Assert.assertEquals(DefaultTomcatSetup.class, setup.getClass());85    //    }86}...Source:AtLeastAndAtMostTest.java  
...23    public ExpectedException exception = ExpectedException.none();24    @Mock25    private IMethods mock;26    @Test27    public void atLeastAtMost_tooLowMinimum() {28        exception.expect(MockitoException.class);29        exception.expectMessage("The minimum number of invocations must be greater that 0!");30        verify(mock, within(100, MILLISECONDS).atLeast(0).andAtMost(5)).simpleMethod();31    }32    @Test33    public void atLeastAtMost_negativeMinimum() {34        exception.expect(MockitoException.class);35        exception.expectMessage("The minimum number of invocations must be greater that 0!");36        verify(mock, within(100, MILLISECONDS).atLeast(-1).andAtMost(5)).simpleMethod();37    }38    @Test39    public void atLeastAtMost_minimumEqualToMax() {40        exception.expect(MockitoException.class);41        exception.expectMessage("The minimum number of invocations must be greater than the maximum!");42        verify(mock, within(100, MILLISECONDS).atLeast(2).andAtMost(2)).simpleMethod();43    }44    @Test45    public void atLeastAtMost_tooLowMaximum() {46        exception.expect(MockitoException.class);47        exception.expectMessage("The maximum number of invocations must be greater than 1!");48        verify(mock, within(100, MILLISECONDS).atLeast(1).andAtMost(0)).simpleMethod();49    }50    @Test51    public void atLeastAtMost_minNumberOfInvocations() {52        mock.simpleMethod();53        verify(mock, within(100, MILLISECONDS).atLeast(1).andAtMost(2)).simpleMethod();54    }55    @Test56    public void atLeastAtMost_maxNumberOfInvocations() {57        mock.simpleMethod();58        mock.simpleMethod();59        verify(mock, within(100, MILLISECONDS).atLeast(1).andAtMost(2)).simpleMethod();60    }61    @Test62    public void atLeastAtMost_tooManyInvocations() {63        exception.expect(TooManyActualInvocations.class);64        exception.expectMessage("mock.simpleMethod()");65        exception.expectMessage("Wanted 2 times");66        exception.expectMessage("But was 3 times");67        mock.simpleMethod();68        mock.simpleMethod();69        mock.simpleMethod();70        verify(mock, within(100, MILLISECONDS).atLeast(1).andAtMost(2)).simpleMethod();71    }72    @Test73    public void atLeastAtMost_tooLittleInvocations() {74        exception.expect(TooLittleActualInvocations.class);75        exception.expectMessage("mock.simpleMethod()");76        exception.expectMessage("Wanted *at least* 1 time");77        exception.expectMessage("But was 0 times");78        verify(mock, within(100, MILLISECONDS).atLeast(1).andAtMost(2)).simpleMethod();79    }80}...Source:GameControllerTest.java  
1package com.controller;2import static org.junit.jupiter.api.Assertions.*;3import static org.mockito.Mockito.atLeast;4import static org.mockito.Mockito.mock;5import static org.mockito.Mockito.times;6import static org.mockito.Mockito.verify;7import static org.mockito.Mockito.when;8import java.util.ArrayList;9import org.junit.jupiter.api.BeforeEach;10import org.junit.jupiter.api.Test;11import org.mockito.InjectMocks;12import org.mockito.Mock;13import org.mockito.MockitoAnnotations;14import org.mockito.internal.verification.AtLeast;15import com.commands.BallChangeXDirectionCommand;16import com.commands.BallEnactCommand;17import com.commands.BrickEnactCommand;18import com.commands.TimerCommand;19import com.component.Ball;20import com.component.Brick;21import com.component.Clock;22import com.component.Paddle;23import com.helper.CollisionChecker;24import com.infrastruture.Direction;25import com.timer.BreakoutTimer;26import com.ui.GUI;27import static org.mockito.ArgumentMatchers.any;28import static org.mockito.Mockito.mock;29class GameControllerTest {30	31	Ball ball;32	Paddle paddle;33	ArrayList<Brick> bricks;34    GUI gui;35    BreakoutTimer observable;36    37    BrickEnactCommand[] brickActCommands;38  	BallEnactCommand ballActCommand;39  	TimerCommand timerCommand;40    Clock clock;41    42  	CollisionChecker collisionChecker;43   44	45    GameController gameController;46	47	@BeforeEach48	void setUp() throws Exception {49		bricks = new ArrayList<>();50		ball = mock(Ball.class);51		paddle = mock(Paddle.class);52		gui = mock(GUI.class);53		observable = mock(BreakoutTimer.class);54		ballActCommand = mock(BallEnactCommand.class);55		timerCommand = mock(TimerCommand.class);56		collisionChecker = mock(CollisionChecker.class);57		clock = mock(Clock.class);58		gameController = new GameController(ball, paddle, bricks, gui, observable, clock, collisionChecker);59		60		//set Command mock61		gameController.setBallActCommand(ballActCommand);	62	}63	64	@Test65	void TestUpdate (){66		gameController.update();67		verify(ballActCommand,atLeast(1)).execute();68		69	}70	@Test71	void TestSave (){72		when(gui.showSaveDialog()).thenReturn("");73		gameController.save();74		verify(gui,atLeast(1)).showSaveDialog();75		76	}77	@Test78	void TestLoad (){79		when(gui.showOpenDialog()).thenReturn("");80		gameController.load();81		verify(gui,atLeast(1)).showOpenDialog();82		83	}84	@Test85	void TestReplay(){86		87		gameController.replay();88		verify(ball,atLeast(1)).reset();89		90	}91}...atLeast
Using AI Code Generation
1public class 1 {2    public void test() {3        List mockedList = mock(List.class);4        mockedList.add("one");5        mockedList.add("two");6        mockedList.add("three");7        mockedList.add("four");8        verify(mockedList, atLeast(2)).add("one");9        verify(mockedList, atLeast(3)).add("two");10        verify(mockedList, atLeast(4)).add("three");11        verify(mockedList, atLeast(5)).add("four");12    }13}14list.add("one");15list.add("one");16-> at 1.test(1.java:7)atLeast
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.runners.MockitoJUnitRunner;5@RunWith(MockitoJUnitRunner.class)6public class MockitoTest {7    public void test() {8        MyInterface mock = mock(MyInterface.class);9        mock.simpleMethod(100);10        verify(mock, atLeast(1)).simpleMethod(100);11    }12}13import static org.mockito.Mockito.*;14import org.junit.Test;15import org.junit.runner.RunWith;16import org.mockito.runners.MockitoJUnitRunner;17@RunWith(MockitoJUnitRunner.class)18public class MockitoTest {19    public void test() {20        MyInterface mock = mock(MyInterface.class);21        mock.simpleMethod(100);22        verify(mock, atLeastOnce()).simpleMethod(100);23    }24}25import static org.mockito.Mockito.*;26import org.junit.Test;27import org.junit.runner.RunWith;28import org.mockito.runners.MockitoJUnitRunner;29@RunWith(MockitoJUnitRunner.class)30public class MockitoTest {31    public void test() {32        MyInterface mock = mock(MyInterface.class);33        mock.simpleMethod(100);34        verify(mock, atMost(1)).simpleMethod(100);35    }36}37import static org.mockito.Mockito.*;38import org.junit.Test;39import org.junit.runner.RunWith;40import org.mockito.runners.MockitoJUnitRunner;41@RunWith(MockitoJUnitRunner.class)42public class MockitoTest {43    public void test() {44        MyInterface mock = mock(MyInterface.class);45        mock.simpleMethod(100);46        verify(mock, never()).simpleMethod(200);47    }48}atLeast
Using AI Code Generation
1import static org.mockito.Mockito.atLeast;2import static org.mockito.Mockito.mock;3import static org.mockito.Mockito.verify;4import java.util.List;5public class Example1 {6	public static void main(String[] args) {7		List mockedList = mock(List.class);8		mockedList.add("one");9		mockedList.clear();10		verify(mockedList).add("one");11		verify(mockedList, atLeast(1)).add("one");12		verify(mockedList, atLeast(2)).add("one");13		verify(mockedList, atLeast(0)).add("one");14	}15}16mockedList.add("one");17-> at Example1.main(Example1.java:17)18mockedList.add("one");19-> at Example1.main(Example1.java:16)201. atLeast(2) will pass212. atLeast(1) will pass223. atLeast(0) will pass234. atLeast(3) will fail245. atLeast(4) will fail256. atLeast(5) will fail267. atLeast(10) will fail278. atLeast(100) will fail289. atLeast(1000) will fail2910. atLeast(10000) will fail3011. atLeast(100000) will fail3112. atLeast(1000000) will fail3213. atLeast(10000000) will fail3314. atLeast(100000000) will fail3415. atLeast(1000000000) will fail3516. atLeast(10000000000) will fail3617. atLeast(100000000000) will fail3718. atLeast(1000000000000) will fail3819. atLeast(10000000000000) will fail3920. atLeast(100000000000000) will fail4021. atLeast(1000000000000000) will fail4122. atLeast(10000000000000000) will fail4223. atLeast(100000000000000000) will fail4324. atLeast(1000000000000000000) will failatLeast
Using AI Code Generation
1package org.example;2import org.junit.Test;3import org.junit.runner.RunWith;4import org.mockito.junit.MockitoJUnitRunner;5import java.util.LinkedList;6import static org.junit.Assert.*;7import static org.mockito.Mockito.*;8@RunWith(MockitoJUnitRunner.class)9public class Test1 {10    public void test1() {11        LinkedList mockedList = mock(LinkedList.class);12        when(mockedList.get(0)).thenReturn("first");13        when(mockedList.get(1)).thenReturn("second");14        System.out.println(mockedList.get(0));15        System.out.println(mockedList.get(1));16        System.out.println(mockedList.get(999));17        verify(mockedList).get(0);18    }19    public void test2() {20        LinkedList mockedList = mock(LinkedList.class);21        when(mockedList.get(anyInt())).thenReturn("element");22        System.out.println(mockedList.get(999));23        verify(mockedList).get(anyInt());24        verify(mockedList).add(argThat(someString -> someString.length() > 5));25        verify(mockedList).add(argThat(someString -> someString.length() > 5), argThat(someString -> someString.length() < 10));26    }27    public void test3() {atLeast
Using AI Code Generation
1import static org.mockito.Mockito.*;2import java.util.LinkedList;3import org.junit.Test;4public class TestMockito {5public void test() {6    LinkedList mockedList = mock(LinkedList.class);7    when(mockedList.get(0)).thenReturn("first");8    when(mockedList.get(1)).thenThrow(new RuntimeException());9    System.out.println(mockedList.get(0));10    System.out.println(mockedList.get(1));11    System.out.println(mockedList.get(999));12    verify(mockedList).get(0);13}14}15    at com.journaldev.mockito.MockitoTest.test(MockitoTest.java:27)16    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)17    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)18    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)19    at java.lang.reflect.Method.invoke(Method.java:606)20    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)21    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)22    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)23    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)24    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)25    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)26    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)27    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)28    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)atLeast
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.junit.Test;3import java.util.List;4public class atLeastTest {5   public void test() {6      List mockedList = mock(List.class);7      mockedList.add("one");8      mockedList.clear();9      verify(mockedList).add("one");10      verify(mockedList).clear();11   }12}13BUILD SUCCESSFUL (total time: 0 seconds)atLeast
Using AI Code Generation
1import org.mockito.Mockito;2import static org.mockito.Mockito.*;3import java.util.List;4public class 1 {5public static void main(String[] args) {6List mockedList = mock(List.class);7when(mockedList.get(anyInt())).thenReturn("element");8verify(mockedList, atLeastOnce()).get(anyInt());9verify(mockedList, atLeast(2)).get(anyInt());10}11}atLeast
Using AI Code Generation
1import static org.mockito.Mockito.*;2import org.mockito.ArgumentMatcher;3import org.mockito.Matchers;4import org.mockito.Mock;5import org.mockito.Mockito;6import org.mockito.MockitoAnnotations;7import org.mockito.stubbing.Answer;8import org.mockito.invocation.InvocationOnMock;9public class MockitoAtLeastExample {10    public static void main(String[] args) {11        MockitoAnnotations.initMocks(MockitoAtLeastExample.class);12        List mockedList = mock(List.class);13        mockedList.add("one");14        mockedList.clear();15        verify(mockedList).add("one");16        verify(mockedList).clear();17        verify(mockedList, times(1)).add("one");18        verify(mockedList, times(1)).clear();19        verify(mockedList, never()).add("two");20        verify(mockedList, never()).add("two");21        verify(mockedList, atLeastOnce()).add("one");22        verify(mockedList, atLeast(2)).add("one");23        verify(mockedList, atMost(5)).add("one");24    }25}26Related Posts: Mockito: How to use atLeastOnce() method of Mockito class27Mockito: How to use atMost() method of Mockito class28Mockito: How to use atLeast() method of Mockito class29Mockito: How to use never() method ofatLeast
Using AI Code Generation
1import static org.mockito.Mockito.*;2import java.util.*;3import org.junit.Test;4public class Test1 {5    public void test() {6        List<String> mockList = mock(List.class);7        when(mockList.get(0)).thenReturn("Hello World");8        System.out.println(mockList.get(0));9        System.out.println(mockList.get(1));10        verify(mockList, atLeast(2)).get(anyInt());11    }12}13mockList.get(1);14-> at Test1.test(Test1.java:14)15import static org.mockito.Mockito.*;16import java.util.*;17import org.junit.Test;18public class Test2 {19    public void test() {20        List<String> mockList = mock(List.class);21        when(mockList.get(0)).thenReturn("Hello World");22        System.out.println(mockList.get(0));23        System.out.println(mockList.get(1));24        verify(mockList, atLeast(0)).get(anyInt());25    }26}atLeast
Using AI Code Generation
1import org.mockito.Mockito;2import org.mockito.InOrder;3public class atLeastMethodExample {4   public static void main(String[] args) {5      List mockedList = Mockito.mock(List.class);6      mockedList.add("one");7      mockedList.clear();8      Mockito.verify(mockedList).add("one");9      Mockito.verify(mockedList, Mockito.times(1)).add("one");10      Mockito.verify(mockedList, Mockito.times(2)).add("one");11      Mockito.verify(mockedList, Mockito.times(1)).clear();12      Mockito.verify(mockedList, Mockito.never()).isEmpty();13      Mockito.verify(mockedList, Mockito.atLeastOnce()).add("one");14      Mockito.verify(mockedList, Mockito.atLeast(2)).add("one");15      Mockito.verify(mockedList, Mockito.atMost(5)).add("one");16   }17}18mockedList.add("one");19-> at atLeastMethodExample.main(atLeastMethodExample.java:15)20-> at atLeastMethodExample.main(atLeastMethodExample.java:14)21at org.mockito.exceptions.verification.VerificationWrapperImpl.createException(VerificationWrapperImpl.java:15)22at org.mockito.exceptions.verification.VerificationWrapperImpl.verificationError(VerificationWrapperImpl.java:39)23at org.mockito.internal.verification.Times.verify(Times.java:42)24at org.mockito.internal.verification.VerificationModeFactory$1.verify(VerificationModeFactory.java:26)25at org.mockito.internal.verification.VerificationModeFactory$AtMost.verify(VerificationModeFactory.java:70)26at org.mockito.internal.handler.MockHandlerImpl.verifyInteraction(MockHandlerImpl.java:84)27at org.mockito.internal.handler.MockHandlerImpl.handle(MockHandlerImpl.java:70)28at org.mockito.internal.handler.NullResultGuardian.handle(NullResultGuardian.java:29)29at org.mockito.internal.handler.InvocationNotifierHandler.handle(InvocationNotifierHandler.java:33)30at org.mockito.internal.creation.cglib.MethodInterceptorFilter.intercept(MethodInterceptorFilter.java:59)Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
