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

The following examples show how to use org.mockito.invocation.InvocationOnMock#callRealMethod() . 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: GenericTestUtils.java    From hadoop with Apache License 2.0 6 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
  boolean interrupted = false;
  try {
    Thread.sleep(r.nextInt(maxSleepTime));
  } catch (InterruptedException ie) {
    interrupted = true;
  }
  try {
    return invocation.callRealMethod();
  } finally {
    if (interrupted) {
      Thread.currentThread().interrupt();
    }
  }
}
 
Example 2
Source File: TestReplicationProcedureRetry.java    From hbase with Apache License 2.0 5 votes vote down vote up
private Object invokeWithError(InvocationOnMock invocation, boolean errorBeforeUpdate)
    throws Throwable {
  if (errorBeforeUpdate) {
    throw new ReplicationException("mock error before update");
  }
  invocation.callRealMethod();
  throw new ReplicationException("mock error after update");
}
 
Example 3
Source File: TestAnswer.java    From influxdb-java with MIT License 5 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
  check(invocation);
  //call only non-abstract real method 
  if (Modifier.isAbstract(invocation.getMethod().getModifiers())) {
    return null;
  } else {
    return invocation.callRealMethod();
  }
}
 
Example 4
Source File: TestTableInputFormat.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Create a table that IOE's on first scanner next call
 *
 * @throws IOException
 */
static Table createIOEScannerTable(byte[] name, final int failCnt)
    throws IOException {
  // build up a mock scanner stuff to fail the first time
  Answer<ResultScanner> a = new Answer<ResultScanner>() {
    int cnt = 0;

    @Override
    public ResultScanner answer(InvocationOnMock invocation) throws Throwable {
      // first invocation return the busted mock scanner
      if (cnt++ < failCnt) {
        // create mock ResultScanner that always fails.
        Scan scan = mock(Scan.class);
        doReturn(Bytes.toBytes("bogus")).when(scan).getStartRow(); // avoid npe
        ResultScanner scanner = mock(ResultScanner.class);
        // simulate TimeoutException / IOException
        doThrow(new IOException("Injected exception")).when(scanner).next();
        return scanner;
      }

      // otherwise return the real scanner.
      return (ResultScanner) invocation.callRealMethod();
    }
  };

  Table htable = spy(createTable(name));
  doAnswer(a).when(htable).getScanner((Scan) anyObject());
  return htable;
}
 
Example 5
Source File: TestTableInputFormat.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Create a table that IOE's on first scanner next call
 *
 * @throws IOException
 */
static Table createIOEScannerTable(byte[] name, final int failCnt)
    throws IOException {
  // build up a mock scanner stuff to fail the first time
  Answer<ResultScanner> a = new Answer<ResultScanner>() {
    int cnt = 0;

    @Override
    public ResultScanner answer(InvocationOnMock invocation) throws Throwable {
      // first invocation return the busted mock scanner
      if (cnt++ < failCnt) {
        // create mock ResultScanner that always fails.
        Scan scan = mock(Scan.class);
        doReturn(Bytes.toBytes("bogus")).when(scan).getStartRow(); // avoid npe
        ResultScanner scanner = mock(ResultScanner.class);
        // simulate TimeoutException / IOException
        doThrow(new IOException("Injected exception")).when(scanner).next();
        return scanner;
      }

      // otherwise return the real scanner.
      return (ResultScanner) invocation.callRealMethod();
    }
  };

  Table htable = spy(createTable(name));
  doAnswer(a).when(htable).getScanner((Scan) anyObject());
  return htable;
}
 
Example 6
Source File: TestEpochsAreUnique.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public ListenableFuture<T> answer(InvocationOnMock invocation)
    throws Throwable {
  if (r.nextFloat() < faultProbability) {
    return Futures.immediateFailedFuture(
        new IOException("Injected fault"));
  }
  return (ListenableFuture<T>)invocation.callRealMethod();
}
 
Example 7
Source File: TestWALProcedureStore.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Test
public void testLogFileAlreadyExists() throws IOException {
  final boolean[] tested = {false};
  WALProcedureStore mStore = Mockito.spy(procStore);

  Answer<Boolean> ans = new Answer<Boolean>() {
    @Override
    public Boolean answer(InvocationOnMock invocationOnMock) throws Throwable {
      long logId = ((Long) invocationOnMock.getArgument(0)).longValue();
      switch ((int) logId) {
        case 2:
          // Create a file so that real rollWriter() runs into file exists condition
          Path logFilePath = mStore.getLogFilePath(logId);
          mStore.getFileSystem().create(logFilePath);
          break;
        case 3:
          // Success only when we retry with logId 3
          tested[0] = true;
        default:
          break;
      }
      return (Boolean) invocationOnMock.callRealMethod();
    }
  };

  // First time Store has one log file, next id will be 2
  Mockito.doAnswer(ans).when(mStore).rollWriter(2);
  // next time its 3
  Mockito.doAnswer(ans).when(mStore).rollWriter(3);

  mStore.recoverLease();
  assertTrue(tested[0]);
}
 
Example 8
Source File: TestTaskSchedulerManager.java    From tez with Apache License 2.0 5 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
  Method method = invocation.getMethod();
  if (method.getDeclaringClass().equals(TaskScheduler.class) &&
      !method.getName().equals("getContext") && !method.getName().equals("initialize") &&
      !method.getName().equals("start") && !method.getName().equals("shutdown")) {
    throw new RuntimeException("TestException_" + method.getName());
  } else {
    return invocation.callRealMethod();
  }
}
 
Example 9
Source File: TestTableInputFormat.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Create a table that throws a NotServingRegionException on first scanner
 * next call
 *
 * @throws IOException
 */
static Table createDNRIOEScannerTable(byte[] name, final int failCnt)
    throws IOException {
  // build up a mock scanner stuff to fail the first time
  Answer<ResultScanner> a = new Answer<ResultScanner>() {
    int cnt = 0;

    @Override
    public ResultScanner answer(InvocationOnMock invocation) throws Throwable {
      // first invocation return the busted mock scanner
      if (cnt++ < failCnt) {
        // create mock ResultScanner that always fails.
        Scan scan = mock(Scan.class);
        doReturn(Bytes.toBytes("bogus")).when(scan).getStartRow(); // avoid npe
        ResultScanner scanner = mock(ResultScanner.class);

        invocation.callRealMethod(); // simulate NotServingRegionException
        doThrow(
            new NotServingRegionException("Injected simulated TimeoutException"))
            .when(scanner).next();
        return scanner;
      }

      // otherwise return the real scanner.
      return (ResultScanner) invocation.callRealMethod();
    }
  };

  Table htable = spy(createTable(name));
  doAnswer(a).when(htable).getScanner((Scan) anyObject());
  return htable;
}
 
Example 10
Source File: GenericTestUtils.java    From big-c with Apache License 2.0 5 votes vote down vote up
protected Object passThrough(InvocationOnMock invocation) throws Throwable {
  try {
    Object ret = invocation.callRealMethod();
    returnValue = ret;
    return ret;
  } catch (Throwable t) {
    thrown = t;
    throw t;
  } finally {
    resultCounter.incrementAndGet();
    resultLatch.countDown();
  }
}
 
Example 11
Source File: TestTableInputFormat.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Create a table that throws a DoNoRetryIOException on first scanner next
 * call
 *
 * @throws IOException
 */
static Table createDNRIOEScannerTable(byte[] name, final int failCnt)
    throws IOException {
  // build up a mock scanner stuff to fail the first time
  Answer<ResultScanner> a = new Answer<ResultScanner>() {
    int cnt = 0;

    @Override
    public ResultScanner answer(InvocationOnMock invocation) throws Throwable {
      // first invocation return the busted mock scanner
      if (cnt++ < failCnt) {
        // create mock ResultScanner that always fails.
        Scan scan = mock(Scan.class);
        doReturn(Bytes.toBytes("bogus")).when(scan).getStartRow(); // avoid npe
        ResultScanner scanner = mock(ResultScanner.class);

        invocation.callRealMethod(); // simulate NotServingRegionException
        doThrow(
            new NotServingRegionException("Injected simulated TimeoutException"))
            .when(scanner).next();
        return scanner;
      }

      // otherwise return the real scanner.
      return (ResultScanner) invocation.callRealMethod();
    }
  };

  Table htable = spy(createTable(name));
  doAnswer(a).when(htable).getScanner((Scan) anyObject());
  return htable;
}
 
Example 12
Source File: TestZKFailoverControllerStress.java    From big-c with Apache License 2.0 5 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
  if (r.nextBoolean()) {
    LOG.info("Throwing an exception for svc " + svcIdx);
    throw new HealthCheckFailedException("random failure");
  }
  return invocation.callRealMethod();
}
 
Example 13
Source File: TestEpochsAreUnique.java    From big-c with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public ListenableFuture<T> answer(InvocationOnMock invocation)
    throws Throwable {
  if (r.nextFloat() < faultProbability) {
    return Futures.immediateFailedFuture(
        new IOException("Injected fault"));
  }
  return (ListenableFuture<T>)invocation.callRealMethod();
}
 
Example 14
Source File: GatewayEventProcessorTest.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
@Override
public T answer(InvocationOnMock invocationOnMock) throws Throwable {
    result = (T) invocationOnMock.callRealMethod();
    return result;
}
 
Example 15
Source File: ResultCaptor.java    From tchannel-java with MIT License 4 votes vote down vote up
@Override
public T answer(InvocationOnMock invocationOnMock) throws Throwable {
    result = (T) invocationOnMock.callRealMethod();
    return result;
}
 
Example 16
Source File: TestEditLogRace.java    From big-c with Apache License 2.0 4 votes vote down vote up
/**
 * Most of the FSNamesystem methods have a synchronized section where they
 * update the name system itself and write to the edit log, and then
 * unsynchronized, they call logSync. This test verifies that, if an
 * operation has written to the edit log but not yet synced it,
 * we wait for that sync before entering safe mode.
 */
@Test
public void testSaveRightBeforeSync() throws Exception {
  Configuration conf = getConf();
  NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
  DFSTestUtil.formatNameNode(conf);
  final FSNamesystem namesystem = FSNamesystem.loadFromDisk(conf);

  try {
    FSImage fsimage = namesystem.getFSImage();
    FSEditLog editLog = spy(fsimage.getEditLog());
    DFSTestUtil.setEditLogForTesting(namesystem, editLog);

    final AtomicReference<Throwable> deferredException =
        new AtomicReference<Throwable>();
    final CountDownLatch waitToEnterSync = new CountDownLatch(1);
    
    final Thread doAnEditThread = new Thread() {
      @Override
      public void run() {
        try {
          LOG.info("Starting mkdirs");
          namesystem.mkdirs("/test",
              new PermissionStatus("test","test", new FsPermission((short)00755)),
              true);
          LOG.info("mkdirs complete");
        } catch (Throwable ioe) {
          LOG.fatal("Got exception", ioe);
          deferredException.set(ioe);
          waitToEnterSync.countDown();
        }
      }
    };
    
    Answer<Void> blockingSync = new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        LOG.info("logSync called");
        if (Thread.currentThread() == doAnEditThread) {
          LOG.info("edit thread: Telling main thread we made it just before logSync...");
          waitToEnterSync.countDown();
          LOG.info("edit thread: sleeping for " + BLOCK_TIME + "secs");
          Thread.sleep(BLOCK_TIME*1000);
          LOG.info("Going through to logSync. This will allow the main thread to continue.");
        }
        invocation.callRealMethod();
        LOG.info("logSync complete");
        return null;
      }
    };
    doAnswer(blockingSync).when(editLog).logSync();
    
    doAnEditThread.start();
    LOG.info("Main thread: waiting to just before logSync...");
    waitToEnterSync.await();
    assertNull(deferredException.get());
    LOG.info("Main thread: detected that logSync about to be called.");
    LOG.info("Trying to enter safe mode.");
    LOG.info("This should block for " + BLOCK_TIME + "sec, since we have pending edits");
    
    long st = Time.now();
    namesystem.setSafeMode(SafeModeAction.SAFEMODE_ENTER);
    long et = Time.now();
    LOG.info("Entered safe mode");
    // Make sure we really waited for the flush to complete!
    assertTrue(et - st > (BLOCK_TIME - 1)*1000);

    // Once we're in safe mode, save namespace.
    namesystem.saveNamespace();

    LOG.info("Joining on edit thread...");
    doAnEditThread.join();
    assertNull(deferredException.get());

    // We did 3 edits: begin, txn, and end
    assertEquals(3, verifyEditLogs(namesystem, fsimage,
        NNStorage.getFinalizedEditsFileName(1, 3),
        1));
    // after the save, just the one "begin"
    assertEquals(1, verifyEditLogs(namesystem, fsimage,
        NNStorage.getInProgressEditsFileName(4),
        4));
  } finally {
    LOG.info("Closing nn");
    if(namesystem != null) namesystem.close();
  }
}
 
Example 17
Source File: DeviceEventProcessorTest.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
@Override
public T answer(InvocationOnMock invocationOnMock) throws Throwable {
    result = (T) invocationOnMock.callRealMethod();
    return result;
}
 
Example 18
Source File: ZooKeeperLeaderElectionTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 *  Test that errors in the {@link LeaderElectionService} are correctly forwarded to the
 *  {@link LeaderContender}.
 */
@Test
public void testExceptionForwarding() throws Exception {
	ZooKeeperLeaderElectionService leaderElectionService = null;
	ZooKeeperLeaderRetrievalService leaderRetrievalService = null;
	TestingListener listener = new TestingListener();
	TestingContender testingContender;

	CuratorFramework client;
	final CreateBuilder mockCreateBuilder = mock(CreateBuilder.class, Mockito.RETURNS_DEEP_STUBS);
	final Exception testException = new Exception("Test exception");

	try {
		client = spy(ZooKeeperUtils.startCuratorFramework(configuration));

		Answer<CreateBuilder> answer = new Answer<CreateBuilder>() {
			private int counter = 0;

			@Override
			public CreateBuilder answer(InvocationOnMock invocation) throws Throwable {
				counter++;

				// at first we have to create the leader latch, there it mustn't fail yet
				if (counter < 2) {
					return (CreateBuilder) invocation.callRealMethod();
				} else {
					return mockCreateBuilder;
				}
			}
		};

		doAnswer(answer).when(client).create();

		when(
			mockCreateBuilder
			.creatingParentsIfNeeded()
			.withMode(Matchers.any(CreateMode.class))
			.forPath(anyString(), any(byte[].class))).thenThrow(testException);

		leaderElectionService = new ZooKeeperLeaderElectionService(client, "/latch", "/leader");
		leaderRetrievalService = ZooKeeperUtils.createLeaderRetrievalService(client, configuration);

		testingContender = new TestingContender(TEST_URL, leaderElectionService);

		leaderElectionService.start(testingContender);
		leaderRetrievalService.start(listener);

		testingContender.waitForError(timeout);

		assertNotNull(testingContender.getError());
		assertEquals(testException, testingContender.getError().getCause());
	} finally {
		if (leaderElectionService != null) {
			leaderElectionService.stop();
		}

		if (leaderRetrievalService != null) {
			leaderRetrievalService.stop();
		}
	}
}
 
Example 19
Source File: TestFileAppend4.java    From RDFS with Apache License 2.0 4 votes vote down vote up
public Object answer(InvocationOnMock invocation) throws Throwable {
  if (delayBefore) doDelay();
  Object ret = invocation.callRealMethod();
  if (!delayBefore) doDelay();
  return ret;
}
 
Example 20
Source File: DiskCliTest.java    From waltz with Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public T answer(InvocationOnMock invocationOnMock) throws Throwable {
    result = (T) invocationOnMock.callRealMethod();
    return result;
}