Search in sources :

Example 76 with InvocationOnMock

use of org.mockito.invocation.InvocationOnMock in project fresco by facebook.

the class DraweeMocks method stubControllerListener.

/**
   * Stubs addControllerListener
   * @param controller
   * @return forwarding listener
   */
public static ControllerListener stubControllerListener(final DraweeController controller) {
    final ForwardingControllerListener forwardingListener = new ForwardingControllerListener();
    if (!(controller instanceof AbstractDraweeController)) {
        return null;
    }
    AbstractDraweeController abstractController = (AbstractDraweeController) controller;
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            forwardingListener.addListener((ControllerListener) invocation.getArguments()[0]);
            return null;
        }
    }).when(abstractController).addControllerListener(any(ControllerListener.class));
    return forwardingListener;
}
Also used : Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ControllerListener(com.facebook.drawee.controller.ControllerListener) ForwardingControllerListener(com.facebook.drawee.controller.ForwardingControllerListener) ForwardingControllerListener(com.facebook.drawee.controller.ForwardingControllerListener) AbstractDraweeController(com.facebook.drawee.controller.AbstractDraweeController)

Example 77 with InvocationOnMock

use of org.mockito.invocation.InvocationOnMock in project fresco by facebook.

the class DraweeMocks method mockBuilderOf.

/**
   * Creates a mock GenericDraweeHierarchyBuilder with stubbed build.
   * @param drawableHierarchies drawable hierarchies to return on {@code build()}
   * @return mock GenericDraweeHierarchyBuilder
   */
public static GenericDraweeHierarchyBuilder mockBuilderOf(GenericDraweeHierarchy... drawableHierarchies) {
    GenericDraweeHierarchyBuilder builder = mock(GenericDraweeHierarchyBuilder.class, CALLS_REAL_METHODS);
    final Supplier<GenericDraweeHierarchy> gdhProvider = supplierOf(drawableHierarchies);
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            return gdhProvider.get();
        }
    }).when(builder).build();
    return builder;
}
Also used : Answer(org.mockito.stubbing.Answer) GenericDraweeHierarchyBuilder(com.facebook.drawee.generic.GenericDraweeHierarchyBuilder) GenericDraweeHierarchy(com.facebook.drawee.generic.GenericDraweeHierarchy) InvocationOnMock(org.mockito.invocation.InvocationOnMock)

Example 78 with InvocationOnMock

use of org.mockito.invocation.InvocationOnMock in project pulsar by yahoo.

the class NamespaceServiceTest method testUnloadNamespaceBundleFailure.

@Test
public void testUnloadNamespaceBundleFailure() throws Exception {
    final String topicName = "persistent://my-property/use/my-ns/my-topic1";
    ConsumerConfiguration conf = new ConsumerConfiguration();
    Consumer consumer = pulsarClient.subscribe(topicName, "my-subscriber-name", conf);
    ConcurrentOpenHashMap<String, CompletableFuture<Topic>> topics = pulsar.getBrokerService().getTopics();
    Topic spyTopic = spy(topics.get(topicName).get());
    topics.clear();
    CompletableFuture<Topic> topicFuture = CompletableFuture.completedFuture(spyTopic);
    // add mock topic
    topics.put(topicName, topicFuture);
    doAnswer(new Answer<CompletableFuture<Void>>() {

        @Override
        public CompletableFuture<Void> answer(InvocationOnMock invocation) throws Throwable {
            CompletableFuture<Void> result = new CompletableFuture<>();
            result.completeExceptionally(new RuntimeException("first time failed"));
            return result;
        }
    }).when(spyTopic).close();
    NamespaceBundle bundle = pulsar.getNamespaceService().getBundle(DestinationName.get(topicName));
    try {
        pulsar.getNamespaceService().unloadNamespaceBundle(bundle);
    } catch (Exception e) {
        // fail
        fail(e.getMessage());
    }
    try {
        pulsar.getLocalZkCache().getZooKeeper().getData(ServiceUnitZkUtils.path(bundle), null, null);
        fail("it should fail as node is not present");
    } catch (org.apache.zookeeper.KeeperException.NoNodeException e) {
    // ok
    }
}
Also used : NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) CompletableFuture(java.util.concurrent.CompletableFuture) Consumer(com.yahoo.pulsar.client.api.Consumer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ConsumerConfiguration(com.yahoo.pulsar.client.api.ConsumerConfiguration) Topic(com.yahoo.pulsar.broker.service.Topic) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) Test(org.testng.annotations.Test)

Example 79 with InvocationOnMock

use of org.mockito.invocation.InvocationOnMock in project pulsar by yahoo.

the class PersistentTopicTest method setupMLAsyncCallbackMocks.

void setupMLAsyncCallbackMocks() {
    ledgerMock = mock(ManagedLedger.class);
    cursorMock = mock(ManagedCursor.class);
    final CompletableFuture<Void> closeFuture = new CompletableFuture<>();
    doReturn(new ArrayList<Object>()).when(ledgerMock).getCursors();
    doReturn("mockCursor").when(cursorMock).getName();
    // doNothing().when(cursorMock).asyncClose(new CloseCallback() {
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            // return closeFuture.get();
            return closeFuture.complete(null);
        }
    }).when(cursorMock).asyncClose(new CloseCallback() {

        @Override
        public void closeComplete(Object ctx) {
            log.info("[{}] Successfully closed cursor ledger", "mockCursor");
            closeFuture.complete(null);
        }

        @Override
        public void closeFailed(ManagedLedgerException exception, Object ctx) {
            // isFenced.set(false);
            log.error("Error closing cursor for subscription", exception);
            closeFuture.completeExceptionally(new BrokerServiceException.PersistenceException(exception));
        }
    }, null);
    // call openLedgerComplete with ledgerMock on ML factory asyncOpen
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerComplete(ledgerMock, null);
            return null;
        }
    }).when(mlFactoryMock).asyncOpen(matches(".*success.*"), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
    // call openLedgerFailed on ML factory asyncOpen
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerFailed(new ManagedLedgerException("Managed ledger failure"), null);
            return null;
        }
    }).when(mlFactoryMock).asyncOpen(matches(".*fail.*"), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
    // call addComplete on ledger asyncAddEntry
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((AddEntryCallback) invocationOnMock.getArguments()[1]).addComplete(new PositionImpl(1, 1), invocationOnMock.getArguments()[2]);
            return null;
        }
    }).when(ledgerMock).asyncAddEntry(any(ByteBuf.class), any(AddEntryCallback.class), anyObject());
    // call openCursorComplete on cursor asyncOpen
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenCursorCallback) invocationOnMock.getArguments()[1]).openCursorComplete(cursorMock, null);
            return null;
        }
    }).when(ledgerMock).asyncOpenCursor(matches(".*success.*"), any(OpenCursorCallback.class), anyObject());
    // call deleteLedgerComplete on ledger asyncDelete
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((DeleteLedgerCallback) invocationOnMock.getArguments()[0]).deleteLedgerComplete(null);
            return null;
        }
    }).when(ledgerMock).asyncDelete(any(DeleteLedgerCallback.class), anyObject());
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((DeleteCursorCallback) invocationOnMock.getArguments()[1]).deleteCursorComplete(null);
            return null;
        }
    }).when(ledgerMock).asyncDeleteCursor(matches(".*success.*"), any(DeleteCursorCallback.class), anyObject());
}
Also used : ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) CloseCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) ByteBuf(io.netty.buffer.ByteBuf) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Answer(org.mockito.stubbing.Answer) CompletableFuture(java.util.concurrent.CompletableFuture) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) DeleteLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteLedgerCallback) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyObject(org.mockito.Matchers.anyObject) DeleteCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback)

Example 80 with InvocationOnMock

use of org.mockito.invocation.InvocationOnMock in project pulsar by yahoo.

the class PersistentTopicTest method testCreateTopic.

@Test
public void testCreateTopic() throws Exception {
    final ManagedLedger ledgerMock = mock(ManagedLedger.class);
    doReturn(new ArrayList<Object>()).when(ledgerMock).getCursors();
    final String topicName = "persistent://prop/use/ns-abc/topic1";
    doAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            ((OpenLedgerCallback) invocationOnMock.getArguments()[2]).openLedgerComplete(ledgerMock, null);
            return null;
        }
    }).when(mlFactoryMock).asyncOpen(anyString(), any(ManagedLedgerConfig.class), any(OpenLedgerCallback.class), anyObject());
    CompletableFuture<Void> future = brokerService.getTopic(topicName).thenAccept(topic -> {
        assertTrue(topic.toString().contains(topicName));
    }).exceptionally((t) -> {
        fail("should not fail");
        return null;
    });
    // wait for completion
    try {
        future.get(1, TimeUnit.SECONDS);
    } catch (Exception e) {
        fail("Should not fail or time out");
    }
}
Also used : SubType(com.yahoo.pulsar.common.api.proto.PulsarApi.CommandSubscribe.SubType) PersistentDispatcherMultipleConsumers(com.yahoo.pulsar.broker.service.persistent.PersistentDispatcherMultipleConsumers) NamespaceService(com.yahoo.pulsar.broker.namespace.NamespaceService) URL(java.net.URL) CloseCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.CloseCallback) LoggerFactory(org.slf4j.LoggerFactory) TimeoutException(java.util.concurrent.TimeoutException) Test(org.testng.annotations.Test) Policies(com.yahoo.pulsar.common.policies.data.Policies) AfterMethod(org.testng.annotations.AfterMethod) Unpooled(io.netty.buffer.Unpooled) Future(java.util.concurrent.Future) OpenCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenCursorCallback) ManagedCursor(org.apache.bookkeeper.mledger.ManagedCursor) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Mockito.atLeast(org.mockito.Mockito.atLeast) DeleteCursorCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCursorCallback) PulsarService(com.yahoo.pulsar.broker.PulsarService) PulsarClientImpl(com.yahoo.pulsar.client.impl.PulsarClientImpl) PulsarClient(com.yahoo.pulsar.client.api.PulsarClient) Mockito.doReturn(org.mockito.Mockito.doReturn) Assert.assertFalse(org.testng.Assert.assertFalse) Method(java.lang.reflect.Method) PositionImpl(org.apache.bookkeeper.mledger.impl.PositionImpl) DestinationName(com.yahoo.pulsar.common.naming.DestinationName) ZooKeeper(org.apache.zookeeper.ZooKeeper) CyclicBarrier(java.util.concurrent.CyclicBarrier) PersistentSubscription(com.yahoo.pulsar.broker.service.persistent.PersistentSubscription) BeforeMethod(org.testng.annotations.BeforeMethod) Mockito.doNothing(org.mockito.Mockito.doNothing) InetSocketAddress(java.net.InetSocketAddress) Executors(java.util.concurrent.Executors) AddEntryCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.AddEntryCallback) Matchers.any(org.mockito.Matchers.any) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) VerificationMode(org.mockito.verification.VerificationMode) CountDownLatch(java.util.concurrent.CountDownLatch) ManagedCursorImpl(org.apache.bookkeeper.mledger.impl.ManagedCursorImpl) AdminResource(com.yahoo.pulsar.broker.admin.AdminResource) PersistentTopic(com.yahoo.pulsar.broker.service.persistent.PersistentTopic) Optional(java.util.Optional) CommandSubscribe(com.yahoo.pulsar.common.api.proto.PulsarApi.CommandSubscribe) Mockito.mock(org.mockito.Mockito.mock) DeleteLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteLedgerCallback) Assert.assertNull(org.testng.Assert.assertNull) ManagedLedgerFactory(org.apache.bookkeeper.mledger.ManagedLedgerFactory) Assert.assertEquals(org.testng.Assert.assertEquals) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ConfigurationCacheService(com.yahoo.pulsar.broker.cache.ConfigurationCacheService) Mockito.spy(org.mockito.Mockito.spy) Matchers.anyString(org.mockito.Matchers.anyString) ProducerConfiguration(com.yahoo.pulsar.client.api.ProducerConfiguration) ArrayList(java.util.ArrayList) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ArgumentCaptor(org.mockito.ArgumentCaptor) Assert(org.testng.Assert) ByteBuf(io.netty.buffer.ByteBuf) Matchers.anyObject(org.mockito.Matchers.anyObject) ConcurrentOpenHashMap(com.yahoo.pulsar.common.util.collections.ConcurrentOpenHashMap) PowerMockito(org.powermock.api.mockito.PowerMockito) ExecutorService(java.util.concurrent.ExecutorService) NamespaceBundle(com.yahoo.pulsar.common.naming.NamespaceBundle) PersistentReplicator(com.yahoo.pulsar.broker.service.persistent.PersistentReplicator) Logger(org.slf4j.Logger) ZooKeeperDataCache(com.yahoo.pulsar.zookeeper.ZooKeeperDataCache) Matchers.matches(org.mockito.Matchers.matches) Assert.fail(org.testng.Assert.fail) PersistentDispatcherSingleActiveConsumer(com.yahoo.pulsar.broker.service.persistent.PersistentDispatcherSingleActiveConsumer) Mockito.when(org.mockito.Mockito.when) Field(java.lang.reflect.Field) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) MessageMetadata(com.yahoo.pulsar.common.api.proto.PulsarApi.MessageMetadata) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) ServiceConfiguration(com.yahoo.pulsar.broker.ServiceConfiguration) Assert.assertTrue(org.testng.Assert.assertTrue) ManagedLedger(org.apache.bookkeeper.mledger.ManagedLedger) Matchers.anyString(org.mockito.Matchers.anyString) TimeoutException(java.util.concurrent.TimeoutException) ManagedLedgerException(org.apache.bookkeeper.mledger.ManagedLedgerException) ExecutionException(java.util.concurrent.ExecutionException) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Matchers.anyObject(org.mockito.Matchers.anyObject) ManagedLedgerConfig(org.apache.bookkeeper.mledger.ManagedLedgerConfig) OpenLedgerCallback(org.apache.bookkeeper.mledger.AsyncCallbacks.OpenLedgerCallback) Test(org.testng.annotations.Test)

Aggregations

InvocationOnMock (org.mockito.invocation.InvocationOnMock)1088 Test (org.junit.Test)655 Answer (org.mockito.stubbing.Answer)287 Matchers.anyString (org.mockito.Matchers.anyString)145 HashMap (java.util.HashMap)124 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)113 Before (org.junit.Before)110 Mockito.doAnswer (org.mockito.Mockito.doAnswer)110 ArrayList (java.util.ArrayList)109 IOException (java.io.IOException)92 Context (android.content.Context)68 List (java.util.List)62 AtomicReference (java.util.concurrent.atomic.AtomicReference)61 CountDownLatch (java.util.concurrent.CountDownLatch)59 Test (org.testng.annotations.Test)59 File (java.io.File)55 UUID (java.util.UUID)46 Configuration (org.apache.hadoop.conf.Configuration)46 Activity (android.app.Activity)40 Semaphore (java.util.concurrent.Semaphore)38