Search in sources :

Example 1 with Answer

use of org.mockito.stubbing.Answer in project camel by apache.

the class CouchbaseProducerTest method testTimeOutRetryThenSuccess.

@Test
public void testTimeOutRetryThenSuccess() throws Exception {
    OperationFuture of = mock(OperationFuture.class);
    when(of.get()).thenAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Exception {
            throw new RuntimeException("Timed out waiting for operation");
        }
    }).thenAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Exception {
            return true;
        }
    });
    when(client.set(org.mockito.Matchers.anyString(), org.mockito.Matchers.anyInt(), org.mockito.Matchers.anyObject(), org.mockito.Matchers.any(PersistTo.class), org.mockito.Matchers.any(ReplicateTo.class))).thenReturn(of);
    when(endpoint.getId()).thenReturn("123");
    when(endpoint.getOperation()).thenReturn("CCB_PUT");
    when(exchange.getOut()).thenReturn(msg);
    producer.process(exchange);
    verify(of, times(2)).get();
    verify(msg).setBody(true);
}
Also used : Answer(org.mockito.stubbing.Answer) ReplicateTo(net.spy.memcached.ReplicateTo) PersistTo(net.spy.memcached.PersistTo) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OperationFuture(net.spy.memcached.internal.OperationFuture) InvalidPayloadException(org.apache.camel.InvalidPayloadException) Test(org.junit.Test)

Example 2 with Answer

use of org.mockito.stubbing.Answer in project camel by apache.

the class CouchbaseProducerTest method testTimeOutRetryTwiceThenSuccess.

@Test
public void testTimeOutRetryTwiceThenSuccess() throws Exception {
    OperationFuture of = mock(OperationFuture.class);
    when(of.get()).thenAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Exception {
            throw new RuntimeException("Timed out waiting for operation");
        }
    }).thenAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Exception {
            throw new RuntimeException("Timed out waiting for operation");
        }
    }).thenAnswer(new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Exception {
            return true;
        }
    });
    when(client.set(org.mockito.Matchers.anyString(), org.mockito.Matchers.anyInt(), org.mockito.Matchers.anyObject(), org.mockito.Matchers.any(PersistTo.class), org.mockito.Matchers.any(ReplicateTo.class))).thenReturn(of);
    when(endpoint.getId()).thenReturn("123");
    when(endpoint.getOperation()).thenReturn("CCB_PUT");
    when(exchange.getOut()).thenReturn(msg);
    producer.process(exchange);
    verify(of, times(3)).get();
    verify(msg).setBody(true);
}
Also used : Answer(org.mockito.stubbing.Answer) ReplicateTo(net.spy.memcached.ReplicateTo) PersistTo(net.spy.memcached.PersistTo) InvocationOnMock(org.mockito.invocation.InvocationOnMock) OperationFuture(net.spy.memcached.internal.OperationFuture) InvalidPayloadException(org.apache.camel.InvalidPayloadException) Test(org.junit.Test)

Example 3 with Answer

use of org.mockito.stubbing.Answer in project flink by apache.

the class StreamTestSingleInputGate method setupInputChannels.

@SuppressWarnings("unchecked")
private void setupInputChannels() throws IOException, InterruptedException {
    for (int i = 0; i < numInputChannels; i++) {
        final int channelIndex = i;
        final RecordSerializer<SerializationDelegate<Object>> recordSerializer = new SpanningRecordSerializer<SerializationDelegate<Object>>();
        final SerializationDelegate<Object> delegate = (SerializationDelegate<Object>) (SerializationDelegate<?>) new SerializationDelegate<StreamElement>(new StreamElementSerializer<T>(serializer));
        inputQueues[channelIndex] = new ConcurrentLinkedQueue<InputValue<Object>>();
        inputChannels[channelIndex] = new TestInputChannel(inputGate, i);
        final Answer<BufferAndAvailability> answer = new Answer<BufferAndAvailability>() {

            @Override
            public BufferAndAvailability answer(InvocationOnMock invocationOnMock) throws Throwable {
                InputValue<Object> input = inputQueues[channelIndex].poll();
                if (input != null && input.isStreamEnd()) {
                    when(inputChannels[channelIndex].getInputChannel().isReleased()).thenReturn(true);
                    return new BufferAndAvailability(EventSerializer.toBuffer(EndOfPartitionEvent.INSTANCE), false);
                } else if (input != null && input.isStreamRecord()) {
                    Object inputElement = input.getStreamRecord();
                    final Buffer buffer = new Buffer(MemorySegmentFactory.allocateUnpooledSegment(bufferSize), mock(BufferRecycler.class));
                    recordSerializer.setNextBuffer(buffer);
                    delegate.setInstance(inputElement);
                    recordSerializer.addRecord(delegate);
                    // Call getCurrentBuffer to ensure size is set
                    return new BufferAndAvailability(recordSerializer.getCurrentBuffer(), false);
                } else if (input != null && input.isEvent()) {
                    AbstractEvent event = input.getEvent();
                    return new BufferAndAvailability(EventSerializer.toBuffer(event), false);
                } else {
                    synchronized (inputQueues[channelIndex]) {
                        inputQueues[channelIndex].wait();
                        return answer(invocationOnMock);
                    }
                }
            }
        };
        when(inputChannels[channelIndex].getInputChannel().getNextBuffer()).thenAnswer(answer);
        inputGate.setInputChannel(new IntermediateResultPartitionID(), inputChannels[channelIndex].getInputChannel());
    }
}
Also used : Buffer(org.apache.flink.runtime.io.network.buffer.Buffer) SerializationDelegate(org.apache.flink.runtime.plugable.SerializationDelegate) SpanningRecordSerializer(org.apache.flink.runtime.io.network.api.serialization.SpanningRecordSerializer) AbstractEvent(org.apache.flink.runtime.event.AbstractEvent) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) BufferAndAvailability(org.apache.flink.runtime.io.network.partition.consumer.InputChannel.BufferAndAvailability) IntermediateResultPartitionID(org.apache.flink.runtime.jobgraph.IntermediateResultPartitionID)

Example 4 with Answer

use of org.mockito.stubbing.Answer in project flink by apache.

the class YarnApplicationMasterRunnerTest method testCreateTaskExecutorContext.

@Test
public void testCreateTaskExecutorContext() throws Exception {
    File root = folder.getRoot();
    File home = new File(root, "home");
    boolean created = home.mkdir();
    assertTrue(created);
    Answer<?> getDefault = new Answer<Object>() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            return invocationOnMock.getArguments()[1];
        }
    };
    Configuration flinkConf = new Configuration();
    YarnConfiguration yarnConf = mock(YarnConfiguration.class);
    doAnswer(getDefault).when(yarnConf).get(anyString(), anyString());
    doAnswer(getDefault).when(yarnConf).getInt(anyString(), anyInt());
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            return new String[] { (String) invocationOnMock.getArguments()[1] };
        }
    }).when(yarnConf).getStrings(anyString(), Mockito.<String>anyVararg());
    Map<String, String> env = ImmutableMap.<String, String>builder().put(ENV_APP_ID, "foo").put(ENV_CLIENT_HOME_DIR, home.getAbsolutePath()).put(ENV_CLIENT_SHIP_FILES, "").put(ENV_FLINK_CLASSPATH, "").put(ENV_HADOOP_USER_NAME, "foo").put(FLINK_JAR_PATH, root.toURI().toString()).build();
    ContaineredTaskManagerParameters tmParams = mock(ContaineredTaskManagerParameters.class);
    Configuration taskManagerConf = new Configuration();
    String workingDirectory = root.getAbsolutePath();
    Class<?> taskManagerMainClass = YarnApplicationMasterRunnerTest.class;
    ContainerLaunchContext ctx = Utils.createTaskExecutorContext(flinkConf, yarnConf, env, tmParams, taskManagerConf, workingDirectory, taskManagerMainClass, LOG);
    assertEquals("file", ctx.getLocalResources().get("flink.jar").getResource().getScheme());
}
Also used : Configuration(org.apache.flink.configuration.Configuration) YarnConfiguration(org.apache.hadoop.yarn.conf.YarnConfiguration) ContaineredTaskManagerParameters(org.apache.flink.runtime.clusterframework.ContaineredTaskManagerParameters) Matchers.anyString(org.mockito.Matchers.anyString) ContainerLaunchContext(org.apache.hadoop.yarn.api.records.ContainerLaunchContext) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) YarnConfiguration(org.apache.hadoop.yarn.conf.YarnConfiguration) InvocationOnMock(org.mockito.invocation.InvocationOnMock) File(java.io.File) Test(org.junit.Test)

Example 5 with Answer

use of org.mockito.stubbing.Answer in project hadoop by apache.

the class TestRMCommunicator method testRMContainerAllocatorYarnRuntimeExceptionIsHandled.

@Test(timeout = 2000)
public void testRMContainerAllocatorYarnRuntimeExceptionIsHandled() throws Exception {
    ClientService mockClientService = mock(ClientService.class);
    AppContext mockContext = mock(AppContext.class);
    MockRMCommunicator mockRMCommunicator = new MockRMCommunicator(mockClientService, mockContext);
    final RMCommunicator communicator = spy(mockRMCommunicator);
    Clock mockClock = mock(Clock.class);
    when(mockContext.getClock()).thenReturn(mockClock);
    doThrow(new YarnRuntimeException("Test")).doNothing().when(communicator).heartbeat();
    when(mockClock.getTime()).thenReturn(1L).thenAnswer(new Answer<Integer>() {

        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            communicator.stop();
            return 2;
        }
    }).thenThrow(new AssertionError("GetClock called second time, when it should not have since the thread " + "should have quit"));
    AllocatorRunnable testRunnable = communicator.new AllocatorRunnable();
    testRunnable.run();
    verify(mockClock, times(2)).getTime();
}
Also used : YarnRuntimeException(org.apache.hadoop.yarn.exceptions.YarnRuntimeException) Answer(org.mockito.stubbing.Answer) ClientService(org.apache.hadoop.mapreduce.v2.app.client.ClientService) InvocationOnMock(org.mockito.invocation.InvocationOnMock) AllocatorRunnable(org.apache.hadoop.mapreduce.v2.app.rm.RMCommunicator.AllocatorRunnable) AppContext(org.apache.hadoop.mapreduce.v2.app.AppContext) Clock(org.apache.hadoop.yarn.util.Clock) Test(org.junit.Test)

Aggregations

Answer (org.mockito.stubbing.Answer)262 InvocationOnMock (org.mockito.invocation.InvocationOnMock)247 Test (org.junit.Test)148 Mockito.doAnswer (org.mockito.Mockito.doAnswer)99 Before (org.junit.Before)36 Matchers.anyString (org.mockito.Matchers.anyString)32 HashMap (java.util.HashMap)31 ArrayList (java.util.ArrayList)30 IOException (java.io.IOException)20 HashSet (java.util.HashSet)16 File (java.io.File)15 AtomicReference (java.util.concurrent.atomic.AtomicReference)15 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)15 Map (java.util.Map)13 List (java.util.List)12 Test (org.testng.annotations.Test)12 CountDownLatch (java.util.concurrent.CountDownLatch)11 Configuration (org.apache.hadoop.conf.Configuration)11 RequestFinishedListener (com.android.volley.RequestQueue.RequestFinishedListener)9 MockRequest (com.android.volley.mock.MockRequest)9