Java Code Examples for org.mockito.stubbing.Answer

The following are top voted examples for showing how to use org.mockito.stubbing.Answer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: q-mail   File: WebDavStoreTest.java   View source code 8 votes vote down vote up
private Answer<HttpResponse> createOkResponseWithCookie() {
    return new Answer<HttpResponse>() {
        @Override
        public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
            HttpContext context = (HttpContext) invocation.getArguments()[1];
            if (context.getAttribute(ClientContext.COOKIE_STORE) != null) {
                BasicCookieStore cookieStore =
                        (BasicCookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
                BasicClientCookie cookie = new BasicClientCookie("cookie", "meLikeCookie");
                cookieStore.addCookie(cookie);
            }

            return OK_200_RESPONSE;
        }
    };
}
 
Example 2
Project: dremio-oss   File: TestFileSystemWrapperFSError.java   View source code 6 votes vote down vote up
@Test
public void test() throws Exception {
  assumeNonMaprProfile();
  final IOException ioException = new IOException("test io exception");
  final FSError fsError = newFSError(ioException);
  FileSystem underlyingFS = mock(FileSystem.class, new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      if (!invocation.getMethod().getName().equals("getScheme")) {
        throw fsError;
      }
      return "mockfs";
    }
  });
  Configuration conf = new Configuration(false);
  FileSystemWrapper fsw = new FileSystemWrapper(conf, underlyingFS, null);
  Object[] params = FSErrorTestUtils.getDummyArguments(method);
  try {
    method.invoke(fsw, params);
  } catch(InvocationTargetException e) {
    assertThat(e.getTargetException(), is(instanceOf(IOException.class)));
    assertThat((IOException) e.getTargetException(), is(sameInstance(ioException)));
  }
}
 
Example 3
Project: empiria.player   File: PowerFeedbackMediatorTest.java   View source code 6 votes vote down vote up
@Test
public void shouldNotifyClientsOnStateChanged_bothClients() {
    // given
    StateChangeEvent event = mockStateChangeEvent(true, false);
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            EndHandler handler = (EndHandler) invocation.getArguments()[0];
            handler.onEnd();
            return null;
        }
    }).when(tutor).processUserInteraction(any(EndHandler.class));
    mediator.registerTutor(tutor);
    mediator.registerBonus(bonus);

    // when
    stateChangedHandler.onStateChange(event);

    // then
    InOrder inOrder = Mockito.inOrder(tutor, bonus);
    inOrder.verify(tutor).processUserInteraction(any(EndHandler.class));
    inOrder.verify(bonus).processUserInteraction();
}
 
Example 4
Project: monarch   File: GMSHealthMonitorJUnitTest.java   View source code 6 votes vote down vote up
@Test
public void testCheckIfAvailableWithSimulatedHeartBeat() {
  NetView v = installAView();

  InternalDistributedMember memberToCheck = mockMembers.get(1);
  HeartbeatMessage fakeHeartbeat = new HeartbeatMessage();
  fakeHeartbeat.setSender(memberToCheck);
  when(messenger.send(any(HeartbeatRequestMessage.class))).then(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      gmsHealthMonitor.processMessage(fakeHeartbeat);
      return null;
    }
  });

  boolean retVal = gmsHealthMonitor.checkIfAvailable(memberToCheck, "Not responding", true);
  assertTrue("CheckIfAvailable should have return true", retVal);
}
 
Example 5
Project: GitHub   File: RequestQueueIntegrationTest.java   View source code 6 votes vote down vote up
/**
 * Verify RequestFinishedListeners are informed when requests are canceled
 *
 * Needs to be an integration test because relies on Request -> dispatcher -> RequestQueue interaction
 */
@Test public void add_requestFinishedListenerCanceled() throws Exception {
    RequestFinishedListener listener = mock(RequestFinishedListener.class);
    Request request = new MockRequest();
    Answer<NetworkResponse> delayAnswer = new Answer<NetworkResponse>() {
        @Override
        public NetworkResponse answer(InvocationOnMock invocationOnMock) throws Throwable {
            Thread.sleep(200);
            return mock(NetworkResponse.class);
        }
    };
    RequestQueue queue = new RequestQueue(new NoCache(), mMockNetwork, 1, mDelivery);

    when(mMockNetwork.performRequest(request)).thenAnswer(delayAnswer);

    queue.addRequestFinishedListener(listener);
    queue.start();
    queue.add(request);

    request.cancel();
    verify(listener, timeout(100)).onRequestFinished(request);
    queue.stop();
}
 
Example 6
Project: empiria.player   File: ExplanationControllerTest.java   View source code 6 votes vote down vote up
@Test
public void shouldCallPlayOrStopEntryOnPlayButtonClick() {
    // given
    String file = "test.mp3";
    Entry entry = mock(Entry.class);
    when(entry.getEntrySound()).thenReturn(file);

    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) {
            clickHandler = (ClickHandler) invocation.getArguments()[0];
            return null;
        }
    }).when(explanationView).addEntryPlayButtonHandler(any(ClickHandler.class));

    // when
    testObj.init();
    testObj.processEntry(entry);
    clickHandler.onClick(null);

    // then
    verify(entryDescriptionSoundController).playOrStopEntrySound(entry.getEntrySound());
}
 
Example 7
Project: GitHub   File: BitmapDrawableTransformationTest.java   View source code 6 votes vote down vote up
@Test
public void testReturnsOriginalResourceIfTransformationDoesNotTransform() {
  int outWidth = 123;
  int outHeight = 456;
  when(wrapped.transform(
      anyContext(), Util.<Bitmap>anyResource(), eq(outWidth), eq(outHeight)))
      .thenAnswer(new Answer<Resource<Bitmap>>() {
        @SuppressWarnings("unchecked")
        @Override
        public Resource<Bitmap> answer(InvocationOnMock invocation) throws Throwable {
          return (Resource<Bitmap>) invocation.getArguments()[1];
        }
      });

  Resource<BitmapDrawable> transformed =
      transformation.transform(context, drawableResourceToTransform, outWidth, outHeight);

  assertThat(transformed).isEqualTo(drawableResourceToTransform);
}
 
Example 8
Project: hadoop-oss   File: TestFileSystemTokens.java   View source code 6 votes vote down vote up
public static MockFileSystem createFileSystemForServiceName(
    final Text service, final FileSystem... children) throws IOException {
  final MockFileSystem fs = new MockFileSystem();
  final MockFileSystem mockFs = fs.getRawFileSystem();
  if (service != null) {
    when(mockFs.getCanonicalServiceName()).thenReturn(service.toString());
    when(mockFs.getDelegationToken(any(String.class))).thenAnswer(
      new Answer<Token<?>>() {
        @Override
        public Token<?> answer(InvocationOnMock invocation) throws Throwable {
          Token<?> token = new Token<TokenIdentifier>();
          token.setService(service);
          return token;
        }
      });
  }
  when(mockFs.getChildFileSystems()).thenReturn(children);
  return fs;
}
 
Example 9
Project: GitHub   File: EngineTest.java   View source code 6 votes vote down vote up
@Test
public void testHandlesNonEngineResourcesFromCacheIfPresent() {
  final Object expected = new Object();
  @SuppressWarnings("rawtypes") Resource fromCache = mockResource();
  when(fromCache.get()).thenReturn(expected);
  when(harness.cache.remove(eq(harness.cacheKey))).thenReturn(fromCache);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      Resource<?> resource = (Resource<?>) invocationOnMock.getArguments()[0];
      assertEquals(expected, resource.get());
      return null;
    }
  }).when(harness.cb).onResourceReady(anyResource(), isADataSource());

  harness.doLoad();

  verify(harness.cb).onResourceReady(anyResource(), isADataSource());
}
 
Example 10
Project: GitHub   File: EngineJobTest.java   View source code 6 votes vote down vote up
@Test
public void testNotifiesNewCallbackOfResourceIfCallbackIsAddedDuringOnResourceReady() {
  final EngineJob<Object> job = harness.getJob();
  final ResourceCallback existingCallback = mock(ResourceCallback.class);
  final ResourceCallback newCallback = mock(ResourceCallback.class);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      job.addCallback(newCallback);
      return null;
    }
  }).when(existingCallback).onResourceReady(anyResource(), isADataSource());

  job.addCallback(existingCallback);
  job.start(harness.decodeJob);
  job.onResourceReady(harness.resource, harness.dataSource);

  verify(newCallback).onResourceReady(eq(harness.engineResource), eq(harness.dataSource));
}
 
Example 11
Project: plugin-id   File: GroupBatchLdapResourceTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Before
public void mockApplicationContext() {
	final ApplicationContext applicationContext = Mockito.mock(ApplicationContext.class);
	SpringUtils.setSharedApplicationContext(applicationContext);
	mockLdapResource = Mockito.mock(GroupResource.class);
	final GroupFullLdapTask mockTask = new GroupFullLdapTask();
	mockTask.resource = mockLdapResource;
	mockTask.securityHelper = securityHelper;
	mockTask.containerScopeResource = Mockito.mock(ContainerScopeResource.class);
	Mockito.when(applicationContext.getBean(SessionSettings.class)).thenReturn(new SessionSettings());
	Mockito.when(applicationContext.getBean((Class<?>) ArgumentMatchers.any(Class.class))).thenAnswer((Answer<Object>) invocation -> {
		final Class<?> requiredType = (Class<Object>) invocation.getArguments()[0];
		if (requiredType == GroupFullLdapTask.class) {
			return mockTask;
		}
		return GroupBatchLdapResourceTest.super.applicationContext.getBean(requiredType);
	});

	final ContainerScope container = new ContainerScope();
	container.setId(1);
	container.setName("Fonction");
	container.setType(ContainerType.GROUP);
	Mockito.when(mockTask.containerScopeResource.findByName("Fonction")).thenReturn(container);
}
 
Example 12
Project: GitHub   File: EngineJobTest.java   View source code 6 votes vote down vote up
@Test
public void testRemovingCallbackDuringOnExceptionIsIgnoredIfCallbackHasAlreadyBeenCalled() {
  harness = new EngineJobHarness();
  final EngineJob<Object> job = harness.getJob();
  final ResourceCallback cb = mock(ResourceCallback.class);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      job.removeCallback(cb);
      return null;
    }
  }).when(cb).onLoadFailed(any(GlideException.class));

  GlideException exception = new GlideException("test");
  job.addCallback(cb);
  job.start(harness.decodeJob);
  job.onLoadFailed(exception);

  verify(cb, times(1)).onLoadFailed(eq(exception));
}
 
Example 13
Project: filestack-java   File: TestClient.java   View source code 6 votes vote down vote up
private static void setupUploadMock(UploadService mockUploadService) {
  String jsonString = "{"
      + "'url' : 'https://s3.amazonaws.com/path',"
      + "'headers' : {"
      + "'Authorization' : 'auth_value',"
      + "'Content-MD5' : 'md5_value',"
      + "'x-amz-content-sha256' : 'sha256_value',"
      + "'x-amz-date' : 'date_value',"
      + "'x-amz-acl' : 'acl_value'"
      + "},"
      + "'location_url' : 'url'"
      + "}";

  Gson gson = new Gson();
  final UploadResponse response = gson.fromJson(jsonString, UploadResponse.class);
  Mockito
      .doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          return Calls.response(response);
        }
      })
      .when(mockUploadService)
      .upload(Mockito.<String, RequestBody>anyMap());
}
 
Example 14
Project: GitHub   File: EngineJobTest.java   View source code 6 votes vote down vote up
@Test
public void testRemovingCallbackDuringOnExceptionPreventsCallbackFromBeingCalledIfNotYetCalled() {
  harness = new EngineJobHarness();
  final EngineJob<Object> job = harness.getJob();
  final ResourceCallback called = mock(ResourceCallback.class);
  final ResourceCallback notYetCalled = mock(ResourceCallback.class);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      job.removeCallback(notYetCalled);
      return null;
    }
  }).when(called).onLoadFailed(any(GlideException.class));

  job.addCallback(called);
  job.addCallback(notYetCalled);
  job.start(harness.decodeJob);
  job.onLoadFailed(new GlideException("test"));

  verify(notYetCalled, never()).onResourceReady(anyResource(), isADataSource());
}
 
Example 15
Project: empiria.player   File: ExplanationControllerTest.java   View source code 6 votes vote down vote up
@Test
public void shouldCallPlayOrStopDescriptionOnPlayButtonClick() {
    // given
    String file = "test.mp3";
    Entry entry = mock(Entry.class);
    when(entry.getEntryExampleSound()).thenReturn(file);

    doAnswer(new Answer<Void>() {
        @Override
        public Void answer(InvocationOnMock invocation) {
            clickHandler = (ClickHandler) invocation.getArguments()[0];
            return null;
        }
    }).when(explanationView).addPlayButtonHandler(any(ClickHandler.class));

    // when
    testObj.init();
    testObj.processEntry(entry);
    clickHandler.onClick(null);

    // then
    verify(explanationDescriptionSoundController).playOrStopExplanationSound(entry.getEntryExampleSound());
}
 
Example 16
Project: oscm   File: OperatorServiceBeanIT.java   View source code 6 votes vote down vote up
@Test
public void testRegisterOrganizationTechnologyProvider_VerifyInvoice()
        throws Exception {
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            if (invocation.getArguments()[0].getClass().equals(PlatformUser.class)) {
                throw new ObjectNotFoundException();
            }
            return invocation.callRealMethod();
        }
    }).when(dataServiceStub).getReferenceByBusinessKey(any(DomainObject.class));
    container.login("me", ROLE_PLATFORM_OPERATOR);
    callerRolles.add(OrganizationRoleType.PLATFORM_OPERATOR);
    final VOOrganization org = newVOOrganization();
    final VOUserDetails user = newVOUser();
    PaymentType pt = new PaymentType();
    pt.setPaymentTypeId(PaymentType.INVOICE);
    dataManager_getReferenceByBusinessKey_return
            .add(new OrganizationRole());
    dataManager_getReferenceByBusinessKey_return.add(pt);
    operatorService.registerOrganization(org, null, user, null, null,
            OrganizationRoleType.TECHNOLOGY_PROVIDER);

    assertTrue(dataManager_persist_objects_orgreftopt.isEmpty());
}
 
Example 17
Project: ContentPal   File: MultiInsertBatchTest.java   View source code 6 votes vote down vote up
@Test
public void testEmpty()
{
    InsertOperation<Object> mockOp = mock(InsertOperation.class);
    when(mockOp.contentOperationBuilder(any(TransactionContext.class))).then(new Answer<ContentProviderOperation.Builder>()
    {
        @Override
        public ContentProviderOperation.Builder answer(InvocationOnMock invocation) throws Throwable
        {
            return ContentProviderOperation.newInsert(Uri.EMPTY);
        }
    });

    assertThat(new MultiInsertBatch<>(mockOp, new Seq<RowData<Object>>()), emptyIterable());
    assertThat(new MultiInsertBatch<>(mockOp, Absent.<RowData<Object>>absent()), emptyIterable());
    assertThat(new MultiInsertBatch<>(mockOp, Absent.<RowData<Object>>absent(), Absent.<RowData<Object>>absent()), emptyIterable());
}
 
Example 18
Project: ditb   File: TestServerNonceManager.java   View source code 6 votes vote down vote up
@Test
public void testStopWaiting() throws Exception {
  final ServerNonceManager nm = createManager();
  nm.setConflictWaitIterationMs(1);
  Stoppable stoppingStoppable = createStoppable();
  Mockito.when(stoppingStoppable.isStopped()).thenAnswer(new Answer<Boolean>() {
    AtomicInteger answer = new AtomicInteger(3);
    @Override
    public Boolean answer(InvocationOnMock invocation) throws Throwable {
      return 0 < answer.decrementAndGet();
    }
  });

  nm.startOperation(NO_NONCE, 1, createStoppable());
  TestRunnable tr = new TestRunnable(nm, 1, null, stoppingStoppable);
  Thread t = tr.start();
  waitForThreadToBlockOrExit(t);
  // thread must eventually throw
  t.join();
  tr.propagateError();
}
 
Example 19
Project: oneops   File: OneopsAuthBrokerTest.java   View source code 6 votes vote down vote up
@Test(priority = 6, expectedExceptions = RuntimeException.class)
public void addProducerTestProducerDenied() {

	//create a mock ConnectionContext which was not used when setting up user map
	ConnectionContext ccForbidden = mock(ConnectionContext.class);
	when(ccForbidden.getClientId()).thenReturn("this-is-not-in-user-map");
	 final Connection connectionMock = mock(Connection.class);
		when(connectionMock.getRemoteAddress()).thenReturn(MOCK_REMOTE_ADDR);
			when(ccForbidden.getConnection()).thenAnswer(new Answer<Connection>() {
		@Override
		public Connection answer(InvocationOnMock invocation)
				throws Throwable {
			return connectionMock;
		}
	});
	
	try {
		this.oneopsAuthBroker.addProducer(ccForbidden, producerInfo);
	} catch (Exception e) {
		logger.warn("caught exception, make sure Broker is mocked",e);
		throw new RuntimeException(e);
	}
}
 
Example 20
Project: hadoop   File: MetricsAsserts.java   View source code 6 votes vote down vote up
public static MetricsRecordBuilder mockMetricsRecordBuilder() {
  final MetricsCollector mc = mock(MetricsCollector.class);
  MetricsRecordBuilder rb = mock(MetricsRecordBuilder.class,
      new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      StringBuilder sb = new StringBuilder();
      for (Object o : args) {
        if (sb.length() > 0) sb.append(", ");
        sb.append(String.valueOf(o));
      }
      String methodName = invocation.getMethod().getName();
      LOG.debug(methodName +": "+ sb);
      return methodName.equals("parent") || methodName.equals("endRecord") ?
             mc : invocation.getMock();
    }
  });
  when(mc.addRecord(anyString())).thenReturn(rb);
  when(mc.addRecord(anyInfo())).thenReturn(rb);
  return rb;
}
 
Example 21
Project: oscm   File: OperatorServiceBeanRevenueShareTest.java   View source code 6 votes vote down vote up
private void mockRegisterOrganization() throws Exception {
    doAnswer(new Answer<Organization>() {
        public Organization answer(InvocationOnMock invocation)
                throws Throwable {
            Object[] args = invocation.getArguments();
            if (args[0] instanceof Organization) {
                createdOrg = (Organization) args[0];
                return createdOrg;
            } else {
                return null;
            }
        }
    }).when(as).registerOrganization(any(Organization.class),
            any(ImageResource.class), any(VOUserDetails.class),
            any(Properties.class), any(String.class), any(String.class),
            any(String.class), any(OrganizationRoleType[].class));
}
 
Example 22
Project: GitHub   File: PickerPresenterTest.java   View source code 6 votes vote down vote up
@Before
public void setupMockAndViews() {
    MockitoAnnotations.initMocks(this);
    PowerMockito.mockStatic(BoxingManager.class);
    PowerMockito.mockStatic(TextUtils.class);
    PowerMockito.when(BoxingManager.getInstance()).thenReturn(mPickerManager);
    mPresenter = new PickerPresenter(mView);
    MockContentResolver contentResolver = new MockContentResolver();

    Mockito.when(mView.getAppCr()).thenReturn(contentResolver);
    PowerMockito.when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            CharSequence charSequence = (CharSequence) invocation.getArguments()[0];
            return !(charSequence != null && charSequence.length() > 0);
        }
    });
}
 
Example 23
Project: spanner-jdbc   File: RunningOperationsStoreTest.java   View source code 6 votes vote down vote up
private Operation<Void, UpdateDatabaseDdlMetadata> mockOperation(boolean error)
{
	@SuppressWarnings("unchecked")
	Operation<Void, UpdateDatabaseDdlMetadata> op = mock(Operation.class);
	when(op.getName()).then(new Returns("TEST_OPERATION"));
	when(op.isDone()).then(new Answer<Boolean>()
	{
		@Override
		public Boolean answer(InvocationOnMock invocation) throws Throwable
		{
			return reportDone;
		}
	});
	when(op.reload()).then(new Returns(op));
	if (error)
		when(op.getResult()).thenThrow(
				SpannerExceptionFactory.newSpannerException(ErrorCode.INVALID_ARGUMENT, "Some exception"));
	else
		when(op.getResult()).then(new Returns(null));
	UpdateDatabaseDdlMetadata metadata = UpdateDatabaseDdlMetadata.getDefaultInstance();
	when(op.getMetadata()).then(new Returns(metadata));

	return op;
}
 
Example 24
Project: pcloud-networking-java   File: RealCallTest.java   View source code 6 votes vote down vote up
@Test
public void testEnqueueWithTimeoutBlocksUntilTimeout() throws Exception {
    Request request = RequestUtils.getUserInfoRequest(Endpoint.DEFAULT);
    final Connection connection = createDummyConnection(Endpoint.DEFAULT, MOCK_EMPTY_ARRAY_RESPONSE);
    mockConnection(connection);

    final RealCall call = getMockRealCall(request, realExecutor);

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Thread.sleep(MOCK_TIMEOUT_TIME);
            return connection.sink();
        }
    }).when(connection).sink();


    assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            call.enqueueAndWait(MOCK_TIMEOUT_TIME, TimeUnit.MILLISECONDS);
        }
    }).isInstanceOf(TimeoutException.class);
}
 
Example 25
Project: GitHub   File: RequestFutureTargetTest.java   View source code 6 votes vote down vote up
@Test
public void testReturnsResourceIfReceivedWhileWaiting()
    throws ExecutionException, InterruptedException {
  final Object expected = new Object();
  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      future.onResourceReady(
          /*resource=*/ expected,
          /*model=*/ null,
          /*target=*/future,
          DataSource.DATA_DISK_CACHE,
          true /*isFirstResource*/);
      return null;
    }
  }).when(waiter).waitForTimeout(eq(future), anyLong());
  assertEquals(expected, future.get());
}
 
Example 26
Project: ditb   File: TestBulkLoad.java   View source code 6 votes vote down vote up
@Test
public void shouldBulkLoadSingleFamilyHLog() throws IOException {
  when(log.append(any(HTableDescriptor.class), any(HRegionInfo.class),
          any(WALKey.class), argThat(bulkLogWalEditType(WALEdit.BULK_LOAD)),
          any(boolean.class))).thenAnswer(new Answer() {
    public Object answer(InvocationOnMock invocation) {
      WALKey walKey = invocation.getArgumentAt(2, WALKey.class);
      MultiVersionConcurrencyControl mvcc = walKey.getMvcc();
      if (mvcc != null) {
        MultiVersionConcurrencyControl.WriteEntry we = mvcc.begin();
        walKey.setWriteEntry(we);
      }
      return 01L;
    };
  });
  testRegionWithFamilies(family1).bulkLoadHFiles(withFamilyPathsFor(family1), false, null);
  verify(log).sync(anyLong());
}
 
Example 27
Project: GitHub   File: EngineTest.java   View source code 6 votes vote down vote up
@Test
public void testHandlesNonEngineResourcesFromCacheIfPresent() {
  final Object expected = new Object();
  @SuppressWarnings("rawtypes") Resource fromCache = mockResource();
  when(fromCache.get()).thenReturn(expected);
  when(harness.cache.remove(eq(harness.cacheKey))).thenReturn(fromCache);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      Resource<?> resource = (Resource<?>) invocationOnMock.getArguments()[0];
      assertEquals(expected, resource.get());
      return null;
    }
  }).when(harness.cb).onResourceReady(anyResource(), isADataSource());

  harness.doLoad();

  verify(harness.cb).onResourceReady(anyResource(), isADataSource());
}
 
Example 28
Project: GitHub   File: DrawableTestUtils.java   View source code 6 votes vote down vote up
/**
 * Stubs setBounds and getBounds methods.
 * @param drawable drawable to stub methods of
 */
public static void stubGetAndSetBounds(Drawable drawable) {
  final Rect rect = new Rect();
  when(drawable.getBounds()).thenReturn(rect);
  doAnswer(
      new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          rect.set(
              (Integer) invocation.getArguments()[0],
              (Integer) invocation.getArguments()[1],
              (Integer) invocation.getArguments()[2],
              (Integer) invocation.getArguments()[3]);
          return null;
        }
      }).when(drawable).setBounds(anyInt(), anyInt(), anyInt(), anyInt());
}
 
Example 29
Project: GitHub   File: EngineTest.java   View source code 6 votes vote down vote up
@Test
public void load_afterResourceIsLoadedAndReleased_returnsFromMemoryCache() {
  harness.cache = new LruResourceCache(100);
  when(harness.resource.isCacheable()).thenReturn(true);
  doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
      harness.getEngine().onEngineJobComplete(harness.cacheKey, harness.resource);
      return null;
    }
  }).when(harness.job).start(any(DecodeJob.class));
  harness.doLoad();
  harness.getEngine().onResourceReleased(harness.cacheKey, harness.resource);
  harness.doLoad();
  verify(harness.cb).onResourceReady(any(Resource.class), eq(DataSource.MEMORY_CACHE));
}
 
Example 30
Project: GitHub   File: EngineTest.java   View source code 6 votes vote down vote up
@Test
public void load_afterResourceIsGcedFromActive_returnsFromMemoryCache() {
  when(harness.resource.getResource()).thenReturn(mock(Resource.class));
  when(harness.resource.isCacheable()).thenReturn(true);
  harness.cache = new LruResourceCache(100);
  doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
      harness.getEngine().onEngineJobComplete(harness.cacheKey, harness.resource);
      return null;
    }
  }).when(harness.job).start(any(DecodeJob.class));
  harness.doLoad();
  ArgumentCaptor<IdleHandler> captor = ArgumentCaptor.forClass(IdleHandler.class);
  verify(GlideShadowLooper.queue).addIdleHandler(captor.capture());
  captor.getValue().queueIdle();
  harness.doLoad();
  verify(harness.cb).onResourceReady(any(Resource.class), eq(DataSource.MEMORY_CACHE));
}
 
Example 31
Project: GitHub   File: EngineJobTest.java   View source code 6 votes vote down vote up
@Test
public void testNotifiesNewCallbackOfResourceIfCallbackIsAddedDuringOnResourceReady() {
  final EngineJob<Object> job = harness.getJob();
  final ResourceCallback existingCallback = mock(ResourceCallback.class);
  final ResourceCallback newCallback = mock(ResourceCallback.class);

  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      job.addCallback(newCallback);
      return null;
    }
  }).when(existingCallback).onResourceReady(anyResource(), isADataSource());

  job.addCallback(existingCallback);
  job.start(harness.decodeJob);
  job.onResourceReady(harness.resource, harness.dataSource);

  verify(newCallback).onResourceReady(eq(harness.engineResource), eq(harness.dataSource));
}
 
Example 32
Project: GitHub   File: BitmapPrepareProducerTest.java   View source code 6 votes vote down vote up
@Before
public void setup() {
  MockitoAnnotations.initMocks(this);

  mImageReference = CloseableReference.of((CloseableImage) mCloseableStaticBitmap);
  when(mCloseableStaticBitmap.getUnderlyingBitmap()).thenReturn(mBitmap);

  // 100 * 15 = 1500 (between MIN_BITMAP_SIZE_BYTES and MAX_BITMAP_SIZE_BYTES)
  when(mBitmap.getRowBytes()).thenReturn(100);
  when(mBitmap.getHeight()).thenReturn(15);

  doAnswer(
          new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
              Object[] args = invocation.getArguments();
              Consumer<CloseableReference<CloseableImage>> consumer =
                  (Consumer<CloseableReference<CloseableImage>>) args[0];
              consumer.onNewResult(mImageReference, 0);
              return null;
            }
          })
      .when(mInputProducer)
      .produceResults(any(Consumer.class), any(ProducerContext.class));
}
 
Example 33
Project: crow   File: MultiJobSchedulerIntegrationTest.java   View source code 6 votes vote down vote up
private Job createJob(final String name, String cronString,int latches) {
    JobDefinition defConsole = new JobDefinition();
    defConsole.setCommand("echo","Hello" + name);
    defConsole.setJobName(name);
    JobExecutor console = new JobExecutor(defConsole, null, null);
    latch.put(name,new CountDownLatch(latches));
    JobExecutor spyConsole = spy(console);
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
            latch.get(name).countDown();
            console.run();
            return null;
        }
    }).when(spyConsole).run();
    IExecutorTemplate template = mock(IExecutorTemplate.class);
    when(template.createExecutor()).thenReturn(console);
    when(template.getJobName()).thenReturn(name);
    return new Job(template, new CronUtilsExecutionTime(cronString));
}
 
Example 34
Project: GitHub   File: NucleusLayoutTest.java   View source code 6 votes vote down vote up
private void setUpPresenter() throws Exception {
    mockPresenter = mock(TestPresenter.class);

    PowerMockito.whenNew(Bundle.class).withNoArguments().thenAnswer(new Answer<Bundle>() {
        @Override
        public Bundle answer(InvocationOnMock invocation) throws Throwable {
            return BundleMock.mock();
        }
    });

    mockDelegate = mock(PresenterLifecycleDelegate.class);
    PowerMockito.whenNew(PresenterLifecycleDelegate.class).withAnyArguments().thenReturn(mockDelegate);
    when(mockDelegate.getPresenter()).thenReturn(mockPresenter);

    mockFactory = mock(ReflectionPresenterFactory.class);
    when(mockFactory.createPresenter()).thenReturn(mockPresenter);

    PowerMockito.mockStatic(ReflectionPresenterFactory.class);
    when(ReflectionPresenterFactory.fromViewClass(any(Class.class))).thenReturn(mockFactory);
}
 
Example 35
Project: flume-release-1.7.0   File: TestKafkaSource.java   View source code 6 votes vote down vote up
ChannelProcessor createGoodChannel() {

    ChannelProcessor channelProcessor = mock(ChannelProcessor.class);

    events = Lists.newArrayList();

    doAnswer(new Answer<Void>() {
      @Override
      public Void answer(InvocationOnMock invocation) throws Throwable {
        events.addAll((List<Event>)invocation.getArguments()[0]);
        return null;
      }
    }).when(channelProcessor).processEventBatch(any(List.class));

    return channelProcessor;
  }
 
Example 36
Project: ysoserial-plus   File: MyfacesTest.java   View source code 6 votes vote down vote up
private static FacesContext createMockFacesContext () throws MalformedURLException {
    FacesContext ctx = Mockito.mock(FacesContext.class);
    CompositeELResolver cer = new CompositeELResolver();
    FacesELContext elc = new FacesELContext(cer, ctx);
    ServletRequest requestMock = Mockito.mock(ServletRequest.class);
    ServletContext contextMock = Mockito.mock(ServletContext.class);
    URL url = new URL("file:///");
    Mockito.when(contextMock.getResource(Matchers.anyString())).thenReturn(url);
    Mockito.when(requestMock.getServletContext()).thenReturn(contextMock);
    Answer<?> attrContext = new MockRequestContext();
    Mockito.when(requestMock.getAttribute(Matchers.anyString())).thenAnswer(attrContext);
    Mockito.doAnswer(attrContext).when(requestMock).setAttribute(Matchers.anyString(), Matchers.any());
    cer.add(new MockELResolver(requestMock));
    cer.add(new BeanELResolver());
    cer.add(new MapELResolver());
    Mockito.when(ctx.getELContext()).thenReturn(elc);
    return ctx;
}
 
Example 37
Project: empiria.player   File: VideoFullScreenHelperTest.java   View source code 6 votes vote down vote up
public void before(String userAgent) {
    BrowserNativeInterface nativeInterface = mock(BrowserNativeInterface.class);
    when(nativeInterface.getUserAgentStrting()).thenReturn(userAgent);
    when(nativeInterface.isUserAgent(anyString(), anyString())).then(new Answer<Boolean>() {
        @Override
        public Boolean answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            Pattern pattern = Pattern.compile(String.valueOf(args[0]));
            return pattern.matcher(String.valueOf(args[1])).find();
        }
    });

    UserAgentChecker.setNativeInterface(nativeInterface);
    setUp(new Class[0], new Class[0], new Class[]{EventsBus.class}, new CustomGuiceModule());
    fullScreenHelper = injector.getInstance(NativeHTML5FullScreenHelper.class);
    instance = injector.getInstance(VideoFullScreenHelper.class);
    instance.postConstruct(); // nie dziala z automatu na mokach
    eventsBus = injector.getInstance(EventsBus.class);

}
 
Example 38
Project: alfresco-repository   File: InviteSenderTest.java   View source code 6 votes vote down vote up
/**
 * Mocks up a FileFolderService that claims there are
 *  no localised templates available
 */
private FileFolderService mockFileFolderService()
{
    FileFolderService fileFolderService = mock(FileFolderService.class);
    when(fileFolderService.getLocalizedSibling( (NodeRef)null )).thenAnswer(
            new Answer<NodeRef>()
            {
                public NodeRef answer(InvocationOnMock invocation) throws Throwable
                {
                    Object[] o = invocation.getArguments();
                    if(o == null || o.length == 0) return null;
                    return (NodeRef)o[0];
                }
            }
    );
    return fileFolderService;
}
 
Example 39
Project: reactive-grpc   File: ReactiveStreamObserverPublisherTest.java   View source code 6 votes vote down vote up
@Test
public void requestDelegates() {
    CallStreamObserver<Object> obs = mock(CallStreamObserver.class);
    Subscriber<Object> sub = mock(Subscriber.class);

    final AtomicReference<Subscription> subscription = new AtomicReference<Subscription>();
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) {
            subscription.set((Subscription) invocationOnMock.getArguments()[0]);
            return null;
        }
    }).when(sub).onSubscribe(any(Subscription.class));

    ReactiveStreamObserverPublisher<Object> pub = new ReactiveStreamObserverPublisher<Object>(obs);
    pub.subscribe(sub);

    assertThat(subscription.get()).isNotNull();
    subscription.get().request(10);
    verify(obs).request(10);
}
 
Example 40
Project: alfresco-repository   File: VirtualizationIntegrationTest.java   View source code 5 votes vote down vote up
protected void prepareMocksCommon(List<ResultSetRow> dbRows)
{
    // make sure we return a new iterator each time
    when(dbResults.iterator()).thenAnswer(new Answer<Iterator<ResultSetRow>>()
    {
        public Iterator<ResultSetRow> answer(org.mockito.invocation.InvocationOnMock invocation) throws Throwable
        {
            return dbRows.iterator();
        };
    });
    when(dbResults.hasMore()).thenReturn(false);
    when(dbResults.getNumberFound()).thenReturn((long) dbRows.size());
    when(dbResults.getStart()).thenReturn(0);
}