private static ExecutorService sameThreadExecutor() throws InterruptedException { ExecutorService executor = immediateExecutor(); when( executor.awaitTermination( anyLong(), any() ) ).thenReturn( true ); doAnswer( invocation -> { ((Runnable) invocation.getArgument( 0 )).run(); return null; } ).when( executor ).execute( any() ); return executor; }
private void prepareMultipleRowsForExecutor() throws KettleException { doReturn( new Object[] { "value1" } ) .doReturn( new Object[] { "value1" } ) .doReturn( new Object[] { "value1" } ) .doReturn( new Object[] { "value1" } ) .doReturn( new Object[] { "value12" } ) .doReturn( new Object[] { "value12" } ) .doReturn( new Object[] { "value12" } ) .doReturn( null ) .when( executor ).getRow(); } }
@Test public void shouldReturnSdkCommand() throws Exception { TfsCommand expectedTfsCommand = mock(TfsCommand.class); TfsCommandFactory spyCommandFactory = spy(tfsCommandFactory); TfsSDKCommandBuilder commandBuilder = mock(TfsSDKCommandBuilder.class); doReturn(commandBuilder).when(spyCommandFactory).getSDKBuilder(); when(commandBuilder.buildTFSSDKCommand("fingerprint", URL, DOMAIN, USERNAME, PASSWORD, computedWorkspaceName, PROJECT_PATH)).thenReturn(expectedTfsCommand); TfsCommand actualTfsCommand = spyCommandFactory.create(executionContext, URL, DOMAIN, USERNAME, PASSWORD, "fingerprint", PROJECT_PATH); assertThat(actualTfsCommand, is(expectedTfsCommand)); verify(commandBuilder).buildTFSSDKCommand("fingerprint", URL, DOMAIN, USERNAME, PASSWORD, computedWorkspaceName, PROJECT_PATH); }
@Test public void load_afterResourceIsLoadedInActiveResources_returnsFromMemoryCache() { when(harness.resource.isCacheable()).thenReturn(true); doAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocationOnMock) { harness.callOnEngineJobComplete(); return null; } }) .when(harness.job) .start(any(DecodeJob.class)); harness.doLoad(); harness.doLoad(); verify(harness.cb).onResourceReady(any(Resource.class), eq(DataSource.MEMORY_CACHE)); }
@Before public void before() throws Exception { MockitoAnnotations.initMocks(this); loader = spy(new FilterLoader(registry, compiler, filterFactory)); doReturn(TestZuulFilter.class).when(compiler).compile(file); when(file.getAbsolutePath()).thenReturn("/filters/in/SomeFilter.groovy"); }
@SuppressWarnings("unchecked") private <T> ModelLoader<T, InputStream> mockStreamModelLoader(final Class<T> modelClass) { ModelLoader<T, InputStream> modelLoader = mock(ModelLoader.class); DataFetcher<InputStream> fetcher = mock(DataFetcher.class); try { doAnswer(new Util.CallDataReady<>(new ByteArrayInputStream(new byte[0]))).when(fetcher) .loadData(isA(Priority.class), isA(DataFetcher.DataCallback.class)); } catch (Exception e) { // Do nothing. } when(fetcher.getDataClass()).thenReturn(InputStream.class); when(modelLoader.buildLoadData(isA(modelClass), anyInt(), anyInt(), isA(Options.class))) .thenReturn(new ModelLoader.LoadData<>(mock(Key.class), fetcher)); when(modelLoader.handles(isA(modelClass))).thenReturn(true); return modelLoader; }
@Test public void shouldReturnFalseifUnableToSetLock() throws IOException { File mockfile = mock(File.class); Lockfile lockfile = spy(new Lockfile(mockfile)); when(mockfile.exists()).thenReturn(false); when(mockfile.getAbsolutePath()).thenReturn("/abcd/dummyFile"); doThrow(new IOException("dummy")).when(lockfile).setHooks(); assertThat(lockfile.tryLock(), is(false)); verify(mockfile).exists(); }
@Test public void shouldReturnChangeSetsFromAPreviouslyKnownRevisionUptilTheLatest() throws Exception { Changeset[] changeSets = getChangeSets(42); when(client.queryHistory(eq(TFS_PROJECT), or(isNull(), any(ChangesetVersionSpec.class)), anyInt())).thenReturn(changeSets); TfsSDKCommand spy = spy(tfsCommand); doReturn(null).when(spy).getModifiedFiles(changeSets[0]); List<Modification> modifications = spy.modificationsSince(null, new StringRevision("2")); assertThat(modifications.isEmpty(), is(false)); verify(client, times(2)).queryHistory(eq(TFS_PROJECT), or(isNull(), any(ChangesetVersionSpec.class)), anyInt()); }
@Test public void interceptConnect_failedReleaseConnection() throws IOException { final DownloadConnection connection = mock(DownloadConnection.class); when(chain.getConnection()).thenReturn(connection); doThrow(IOException.class).doReturn(connected).when(chain).processConnect(); thrown.expect(IOException.class); interceptor.interceptConnect(chain); verify(cache).catchException(any(IOException.class)); verify(outputStream).catchBlockConnectException(anyInt()); }
private OutputCommitter setupOutputCommitter(boolean needsTaskCommit) throws IOException { OutputCommitter outputCommitter = Mockito.mock(OutputCommitter.class); when(outputCommitter.needsTaskCommit(nullable(TaskAttemptContext.class))).thenReturn(needsTaskCommit); doNothing().when(outputCommitter).commitTask(any(TaskAttemptContext.class)); return outputCommitter; }
@Test public void testDelegateFailureAtWarmUp() { when(delegateResolver.getClusterEndpoints()) .thenReturn(null); // override the scheduling which will be triggered immediately if warmUp fails (as is intended). // do this to avoid thread race conditions for a more predictable test doNothing().when(resolver).scheduleTask(anyLong()); List endpoints = resolver.getClusterEndpoints(); assertThat(endpoints.isEmpty(), is(true)); verify(delegateResolver, times(1)).getClusterEndpoints(); verify(resolver, times(1)).doWarmUp(); } }
@Test(expected = AccessDeniedException.class) public void preSendDeny() throws Exception { when(source.getAttributes(message)).thenReturn(attrs); doThrow(new AccessDeniedException("")).when(accessDecisionManager).decide( any(Authentication.class), eq(message), eq(attrs)); interceptor.preSend(message, channel); }
public HStore createStoreMock(String name) throws Exception { HStore store = mock(HStore.class, name); when(store.requestCompaction(anyInt(), any(), any())).then(inv -> selectCompaction()); when(store.getCompactPriority()).then(inv -> getPriority()); doAnswer(new CancelAnswer()).when(store).cancelRequestedCompaction(any()); return store; } }
@Test public void testGroupCreateExistingFails() { Group newGroup = MockProvider.createMockGroup(); when(identityServiceMock.newGroup(MockProvider.EXAMPLE_GROUP_ID)).thenReturn(newGroup); doThrow(new ProcessEngineException("")).when(identityServiceMock).saveGroup(newGroup); given().body(GroupDto.fromGroup(newGroup)).contentType(ContentType.JSON) .then().expect().statusCode(Status.INTERNAL_SERVER_ERROR.getStatusCode()).contentType(ContentType.JSON) .body("type", equalTo(ProcessEngineException.class.getSimpleName())) .when().post(GROUP_CREATE_URL); verify(identityServiceMock).newGroup(MockProvider.EXAMPLE_GROUP_ID); verify(identityServiceMock).saveGroup(newGroup); }
@GwtIncompatible // Mockito public void testOnSuccessThrowsRuntimeException() throws Exception { RuntimeException exception = new RuntimeException(); String result = "result"; SettableFuture<String> future = SettableFuture.create(); @SuppressWarnings("unchecked") // Safe for a mock FutureCallback<String> callback = Mockito.mock(FutureCallback.class); addCallback(future, callback, directExecutor()); Mockito.doThrow(exception).when(callback).onSuccess(result); future.set(result); assertEquals(result, future.get()); Mockito.verify(callback).onSuccess(result); Mockito.verifyNoMoreInteractions(callback); }
static Resources mockResources(final String resValueString) { Resources resources = mock(Resources.class); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Object[] args = invocation.getArguments(); ((TypedValue) args[1]).string = resValueString; return null; } }).when(resources).getValue(anyInt(), any(TypedValue.class), anyBoolean()); return resources; }
@Before public void setUp() { MockitoAnnotations.initMocks(this); doAnswer(new AddBitmapPoolAnswer(addedBitmaps)).when(pool).put(any(Bitmap.class)); when(pool.getDirty(anyInt(), anyInt(), any(Bitmap.Config.class))) .thenAnswer(new CreateBitmap()); when(cache.put(any(Key.class), anyResource())) .thenAnswer(new AddBitmapCacheAnswer(addedBitmaps)); }
@Before public void setUp() throws UnsupportedEncodingException { MockitoAnnotations.initMocks(this); doAnswer(new WriteDigest("firstKey")).when(firstKey) .updateDiskCacheKey(any(MessageDigest.class)); doAnswer(new WriteDigest("firstSignature")).when(firstSignature) .updateDiskCacheKey(any(MessageDigest.class)); doAnswer(new WriteDigest("secondKey")).when(secondKey) .updateDiskCacheKey(any(MessageDigest.class)); doAnswer(new WriteDigest("secondSignature")).when(secondSignature) .updateDiskCacheKey(any(MessageDigest.class)); }
/** * Do Cache full exception * @throws IOException * @throws InterruptedException */ @Test public void testCacheFullException() throws IOException, InterruptedException { this.bc.cacheBlock(this.plainKey, plainCacheable); RAMQueueEntry rqe = q.remove(); RAMQueueEntry spiedRqe = Mockito.spy(rqe); final CacheFullException cfe = new CacheFullException(0, 0); BucketEntry mockedBucketEntry = Mockito.mock(BucketEntry.class); Mockito.doThrow(cfe). doReturn(mockedBucketEntry). when(spiedRqe).writeToCache(Mockito.any(), Mockito.any(), Mockito.any()); this.q.add(spiedRqe); doDrainOfOneEntry(bc, wt, q); }