Java Code Examples for org.mockito.invocation.InvocationOnMock#getArgument()

The following examples show how to use org.mockito.invocation.InvocationOnMock#getArgument() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractWeightedFairQueueByteDistributorDependencyTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
Answer<Void> writeAnswer(final boolean closeIfNoFrame) {
    return new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock in) throws Throwable {
            Http2Stream stream = in.getArgument(0);
            int numBytes = in.getArgument(1);
            TestStreamByteDistributorStreamState state = stateMap.get(stream.id());
            state.pendingBytes -= numBytes;
            state.hasFrame = state.pendingBytes > 0;
            state.isWriteAllowed = state.hasFrame;
            if (closeIfNoFrame && !state.hasFrame) {
                stream.close();
            }
            distributor.updateStreamableBytes(state);
            return null;
        }
    };
}
 
Example 2
Source File: ITJettyWebSocketCommunication.java    From nifi with Apache License 2.0 6 votes vote down vote up
protected Object assertConsumeBinaryMessage(CountDownLatch latch, String expectedMessage, InvocationOnMock invocation) {
    final WebSocketSessionInfo sessionInfo = invocation.getArgument(0);
    assertNotNull(sessionInfo.getLocalAddress());
    assertNotNull(sessionInfo.getRemoteAddress());
    assertNotNull(sessionInfo.getSessionId());
    assertEquals(isSecure(), sessionInfo.isSecure());

    final byte[] receivedMessage = invocation.getArgument(1);
    final byte[] expectedBinary = expectedMessage.getBytes();
    final int offset = invocation.getArgument(2);
    final int length = invocation.getArgument(3);
    assertNotNull(receivedMessage);
    assertEquals(expectedBinary.length, receivedMessage.length);
    assertEquals(expectedMessage, new String(receivedMessage));
    assertEquals(0, offset);
    assertEquals(expectedBinary.length, length);
    latch.countDown();
    return null;
}
 
Example 3
Source File: TaskExecutorTest.java    From incubator-nemo with Apache License 2.0 6 votes vote down vote up
@Override
public InputReader answer(final InvocationOnMock invocationOnMock) throws Throwable {
  final List<CompletableFuture<DataUtil.IteratorWithNumBytes>> inputFutures = new ArrayList<>(SOURCE_PARALLELISM);
  final int elementsPerSource = DATA_SIZE / SOURCE_PARALLELISM;
  for (int i = 0; i < SOURCE_PARALLELISM; i++) {
    inputFutures.add(CompletableFuture.completedFuture(
      DataUtil.IteratorWithNumBytes.of(elements.subList(i * elementsPerSource, (i + 1) * elementsPerSource)
        .iterator())));
  }
  final InputReader inputReader = mock(InputReader.class);
  final IRVertex srcVertex = (IRVertex) invocationOnMock.getArgument(1);
  srcVertex.setProperty(ParallelismProperty.of(SOURCE_PARALLELISM));
  when(inputReader.getSrcIrVertex()).thenReturn(srcVertex);
  when(inputReader.read()).thenReturn(inputFutures);
  when(inputReader.getProperties()).thenReturn(new ExecutionPropertyMap<>(""));
  return inputReader;
}
 
Example 4
Source File: SecretsManagerTest.java    From fernet-java8 with Apache License 2.0 6 votes vote down vote up
@Test
public final void verifyPutSecretValueStoresKey() throws IOException {
    // given
    final String expected = "expected";
    final Key key = mock(Key.class);
    final Answer<?> answer = new Answer<Void>() {
        public Void answer(final InvocationOnMock invocation) throws Throwable {
            final OutputStream stream = invocation.getArgument(0);
            stream.write(expected.getBytes("UTF-8"));
            return null;
        }
    };
    doAnswer(answer).when(key).writeTo(any(OutputStream.class));

    // when
    manager.putSecretValue("secret", "version", key, PREVIOUS);

    // then
    final PutSecretValueRequest request = new PutSecretValueRequest();
    request.setSecretId("secret");
    request.setClientRequestToken("version");
    request.setVersionStages(singleton("AWSPREVIOUS"));
    request.setSecretBinary(ByteBuffer.wrap(expected.getBytes("UTF-8")));
    verify(delegate).putSecretValue(eq(request));
}
 
Example 5
Source File: IdeaLightweightExtension.java    From p4ic4idea with Apache License 2.0 6 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation)
        throws Throwable {
    final Object arg = invocation.getArgument(0);
    final Runnable runner;
    if (arg instanceof Runnable) {
        runner = (Runnable) arg;
    } else {
        runner = () -> {
            try {
                ((Callable<?>) arg).call();
            } catch (Exception e) {
                fail(e);
            }
        };
    }
    runner.run();
    return null;
}
 
Example 6
Source File: PlaylistServiceTestImport.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocationOnMock) {
    File file = invocationOnMock.getArgument(0);
    MediaFile mediaFile = new MediaFile();
    mediaFile.setPath(file.getPath());
    return mediaFile;
}
 
Example 7
Source File: UniformStreamByteDistributorTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
private Answer<Void> writeAnswer() {
    return new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock in) throws Throwable {
            Http2Stream stream = in.getArgument(0);
            int numBytes = in.getArgument(1);
            TestStreamByteDistributorStreamState state = stateMap.get(stream.id());
            state.pendingBytes -= numBytes;
            state.hasFrame = state.pendingBytes > 0;
            distributor.updateStreamableBytes(state);
            return null;
        }
    };
}
 
Example 8
Source File: FetchRecentBlocksServiceTest.java    From teku with Apache License 2.0 5 votes vote down vote up
private FetchBlockTask createMockTask(final InvocationOnMock invocationOnMock) {
  Bytes32 blockRoot = invocationOnMock.getArgument(1);
  final FetchBlockTask task = mock(FetchBlockTask.class);

  lenient().when(task.getBlockRoot()).thenReturn(blockRoot);
  lenient().when(task.getNumberOfRetries()).thenReturn(0);
  final SafeFuture<FetchBlockResult> future = new SafeFuture<>();
  lenient().when(task.run()).thenReturn(future);
  taskFutures.add(future);

  tasks.add(task);

  return task;
}
 
Example 9
Source File: SecretsManagerTest.java    From fernet-java8 with Apache License 2.0 5 votes vote down vote up
@Test
public final void verifyPutSecretValueStoresKeys() throws IOException {
    // given
    final String expected = "expected";
    final Key key0 = mock(Key.class);
    final Key key1 = mock(Key.class);
    final Answer<?> answer = new Answer<Void>() {
        public Void answer(final InvocationOnMock invocation) throws Throwable {
            final OutputStream stream = invocation.getArgument(0);
            stream.write(expected.getBytes("UTF-8"));
            return null;
        }
    };
    doAnswer(answer).when(key0).writeTo(any(OutputStream.class));
    doAnswer(answer).when(key1).writeTo(any(OutputStream.class));

    // when
    manager.putSecretValue("secret", "version", asList(key0, key1), PREVIOUS);

    // then
    final PutSecretValueRequest request = new PutSecretValueRequest();
    request.setSecretId("secret");
    request.setClientRequestToken("version");
    request.setVersionStages(singleton("AWSPREVIOUS"));
    request.setSecretBinary(ByteBuffer.wrap((expected + expected).getBytes("UTF-8")));
    verify(delegate).putSecretValue(eq(request));
}
 
Example 10
Source File: CustomAnswerWithoutLambdaUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public Stream<JobPosition> answer(InvocationOnMock invocation) throws Throwable {
    Person person = invocation.getArgument(0);
    
    if(person.getName().equals("Peter")) {
        return Stream.<JobPosition>builder().add(new JobPosition("Teacher")).build();
    } 
    
    return Stream.empty();
}
 
Example 11
Source File: ITJettyWebSocketCommunication.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected Object assertConsumeTextMessage(CountDownLatch latch, String expectedMessage, InvocationOnMock invocation) {
    final WebSocketSessionInfo sessionInfo = invocation.getArgument(0);
    assertNotNull(sessionInfo.getLocalAddress());
    assertNotNull(sessionInfo.getRemoteAddress());
    assertNotNull(sessionInfo.getSessionId());
    assertEquals(isSecure(), sessionInfo.isSecure());

    final String receivedMessage = invocation.getArgument(1);
    assertNotNull(receivedMessage);
    assertEquals(expectedMessage, receivedMessage);
    latch.countDown();
    return null;
}
 
Example 12
Source File: MongoDbSinkTaskTest.java    From MongoDb-Sink-Connector with Apache License 2.0 5 votes vote down vote up
@Override
public MongoDbWriter answer(InvocationOnMock invocation) {
    foundBuffer = invocation.getArgument(1);
    foundFactory = invocation.getArgument(4);
    timesCalled++;
    return writer;
}
 
Example 13
Source File: ITJettyWebSocketCommunication.java    From nifi with Apache License 2.0 5 votes vote down vote up
protected Object assertConnectedEvent(CountDownLatch latch, AtomicReference<String> sessionIdRef, InvocationOnMock invocation) {
    final WebSocketSessionInfo sessionInfo = invocation.getArgument(0);
    assertNotNull(sessionInfo.getLocalAddress());
    assertNotNull(sessionInfo.getRemoteAddress());
    assertNotNull(sessionInfo.getSessionId());
    assertEquals(isSecure(), sessionInfo.isSecure());
    sessionIdRef.set(sessionInfo.getSessionId());
    latch.countDown();
    return null;
}
 
Example 14
Source File: TestHelper.java    From Cashier with Apache License 2.0 5 votes vote down vote up
static Threading mockThreading() {
    Threading mock = mock(Threading.class);
    Answer executeAnswer = new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Runnable runnable = invocation.getArgument(0);
            runnable.run();
            return null;
        }
    };
    doAnswer(executeAnswer).when(mock).runOnMainThread(any(Runnable.class));
    doAnswer(executeAnswer).when(mock).runInBackground(any(Runnable.class));
    return mock;
}
 
Example 15
Source File: MockThreadRunner.java    From p4ic4idea with Apache License 2.0 5 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation)
        throws Throwable {
    activeCount.incrementAndGet();
    try {
        Runnable runnable = invocation.getArgument(0);
        counter.incrementAndGet();
        runnable.run();
    } finally {
        activeCount.decrementAndGet();
    }
    return null;
}
 
Example 16
Source File: MetricTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private Cluster saveCluster(InvocationOnMock i) {
    Cluster cluster = i.getArgument(0);
    cluster.setClusterPertain(getClusterPertain());
    cluster.setId(CLUSTER_ID);
    return cluster;
}
 
Example 17
Source File: VirtualMachineForHotSpotTest.java    From byte-buddy with Apache License 2.0 4 votes vote down vote up
public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
    byte[] buffer = invocationOnMock.getArgument(0);
    System.arraycopy(value, 0, buffer, 0, value.length);
    return value.length;
}
 
Example 18
Source File: BatchOptionsTest.java    From influxdb-java with MIT License 4 votes vote down vote up
/**
 * Test the implementation of {@link BatchOptions#consistency(InfluxDB.ConsistencyLevel)} }.
 * @throws InterruptedException
 */
@Test
public void testConsistency() throws InterruptedException {
  String dbName = "write_unittest_" + System.currentTimeMillis();

  InfluxDB spy = spy(influxDB);
  spy.query(new Query("CREATE DATABASE " + dbName));
  spy.setDatabase(dbName);
  try {
    TestAnswer answer = new TestAnswer() {
      @Override
      protected void check(InvocationOnMock invocation) {
        BatchPoints batchPoints = (BatchPoints) invocation.getArgument(0);
        Assertions.assertEquals(params.get("consistencyLevel"), batchPoints.getConsistency());

      }
    };
    doAnswer(answer).when(spy).write(any(BatchPoints.class));

    int n = 0;
    for (final ConsistencyLevel consistencyLevel : ConsistencyLevel.values()) {
      answer.params.put("consistencyLevel", consistencyLevel);
      BatchOptions options = BatchOptions.DEFAULTS.consistency(consistencyLevel).flushDuration(100);
      spy.enableBatch(options);
      Assertions.assertEquals(options.getConsistency(), consistencyLevel);

      writeSomePoints(spy, n, n + 4);
      n += 5;
      Thread.sleep(300);

      verify(spy, atLeastOnce()).write(any(BatchPoints.class));
      QueryResult result = spy.query(new Query("select * from weather", dbName));
      Assertions.assertEquals(n, result.getResults().get(0).getSeries().get(0).getValues().size());


      spy.disableBatch();
    }

  } finally {
    spy.query(new Query("DROP DATABASE " + dbName));
  }
}
 
Example 19
Source File: PlaylistServiceTestImport.java    From airsonic with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocationOnMock) {
    Playlist playlist = invocationOnMock.getArgument(0);
    playlist.setId(id);
    return null;
}
 
Example 20
Source File: FileSystemConfigServiceTest.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private FileSystem setIdForCreatedFileSystemEntry(InvocationOnMock invocation) {
    FileSystem fileSystem = invocation.getArgument(0);
    fileSystem.setId(TEST_FILES_SYSTEM_ID);
    return fileSystem;
}