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   Source Code and License 9 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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);
}
 
Example 41
Project: ditb   File: HConnectionTestingUtility.java   Source Code and License 5 votes vote down vote up
/**
 * @param connection
 */
private static void mockRegionLocator(final HConnectionImplementation connection) {
  try {
    Mockito.when(connection.getRegionLocator(Mockito.any(TableName.class))).thenAnswer(
        new Answer<RegionLocator>() {
          @Override
          public RegionLocator answer(InvocationOnMock invocation) throws Throwable {
            TableName tableName = (TableName) invocation.getArguments()[0];
            return new HRegionLocator(tableName, connection);
          }
        });
  } catch (IOException e) {
  }
}
 
Example 42
Project: oscm   File: PartnerRevenueBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void processService_createRevenueDetailService() throws Exception {
    // given
    PartnerRevenueBuilder builder = spy(new PartnerRevenueBuilder(
            Locale.ENGLISH, null));

    doReturn("1").when(builder).readServiceRevenue(anyString(),
            anyString(), anyString());
    doReturn("423").when(builder).getServiceKey(any(Node.class));

    doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            return null;
        }
    }).when(builder).createRevenueDetailService(anyInt(), anyString(),
            anyString(), anyString());

    List<RDORevenueDetailService> result = new LinkedList<RDORevenueDetailService>();
    Node dummyService = null;

    // when
    builder.processService(result, 0, dummyService, "dummy", "dummy");

    // then
    assertEquals(1, result.size());
    verify(builder, times(1)).createRevenueDetailService(anyInt(),
            anyString(), anyString(), anyString());
}
 
Example 43
Project: ditb   File: TestSimpleRpcScheduler.java   Source Code and License 5 votes vote down vote up
private void doAnswerTaskExecution(final CallRunner callTask,
    final ArrayList<Integer> results, final int value, final int sleepInterval) {
  callTask.setStatus(new MonitoredRPCHandlerImpl());
  doAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) {
      synchronized (results) {
        results.add(value);
      }
      Threads.sleepWithoutInterrupt(sleepInterval);
      return null;
    }
  }).when(callTask).run();
}
 
Example 44
Project: q-mail   File: WebDavFolderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void folder_does_not_notify_listener_twice_when_fetching_flags_and_bodies()
        throws MessagingException, IOException, URISyntaxException {
    setupStoreForMessageFetching();
    when(mockStore.processRequest(anyString(), anyString(), anyString(),
            anyMapOf(String.class, String.class)))
            .thenReturn(mockDataSet);
    List<WebDavMessage> messages = setup25MessagesToFetch();
    when(mockHttpClient.executeOverride(any(HttpUriRequest.class), any(HttpContext.class))).thenAnswer(
            new Answer<HttpResponse>() {
                @Override
                public HttpResponse answer(InvocationOnMock invocation) throws Throwable {
                    HttpResponse httpResponse = mock(HttpResponse.class);
                    StatusLine statusLine = mock(StatusLine.class);
                    when(httpResponse.getStatusLine()).thenReturn(statusLine);
                    when(statusLine.getStatusCode()).thenReturn(200);

                    BasicHttpEntity httpEntity = new BasicHttpEntity();
                    String body = "";
                    httpEntity.setContent(new ByteArrayInputStream(body.getBytes("UTF-8")));
                    when(httpResponse.getEntity()).thenReturn(httpEntity);
                    return httpResponse;
                }
            });

    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.FLAGS);
    profile.add(FetchProfile.Item.BODY);
    folder.fetch(messages, profile, listener);
    verify(listener, times(25)).messageStarted(any(String.class), anyInt(), anyInt());
    verify(listener, times(25)).messageFinished(any(WebDavMessage.class), anyInt(), anyInt());
}
 
Example 45
Project: Webcheckers   File: MyModelAndView.java   Source Code and License 5 votes vote down vote up
/**
 *
 * @param myModelView
 * @return
 */
static Answer<Object> makeAnswer(final MyModelAndView myModelView) {
    return new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            final ModelAndView modelAndView = invocation.getArgument(0);
            myModelView.model = modelAndView.getModel();
            myModelView.viewName = modelAndView.getViewName();
            // the return value is not of interest
            return null;
        }
    };
}
 
Example 46
Project: RNLearn_Project1   File: NetworkingModuleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGetWithoutHeaders() throws Exception {
  OkHttpClient httpClient = mock(OkHttpClient.class);
  when(httpClient.newCall(any(Request.class))).thenAnswer(new Answer<Object>() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      Call callMock = mock(Call.class);
      return callMock;
    }
  });
  OkHttpClient.Builder clientBuilder = mock(OkHttpClient.Builder.class);
  when(clientBuilder.build()).thenReturn(httpClient);
  when(httpClient.newBuilder()).thenReturn(clientBuilder);
  NetworkingModule networkingModule =
    new NetworkingModule(mock(ReactApplicationContext.class), "", httpClient);

  networkingModule.sendRequest(
    mock(ExecutorToken.class),
    "GET",
    "http://somedomain/foo",
    /* requestId */ 0,
    /* headers */ JavaOnlyArray.of(),
    /* body */ null,
    /* responseType */ "text",
    /* useIncrementalUpdates*/ true,
    /* timeout */ 0,
    /* withCredentials */ false);

  ArgumentCaptor<Request> argumentCaptor = ArgumentCaptor.forClass(Request.class);
  verify(httpClient).newCall(argumentCaptor.capture());
  assertThat(argumentCaptor.getValue().url().toString()).isEqualTo("http://somedomain/foo");
  // We set the User-Agent header by default
  assertThat(argumentCaptor.getValue().headers().size()).isEqualTo(1);
  assertThat(argumentCaptor.getValue().method()).isEqualTo("GET");
}
 
Example 47
Project: AndroidSnooper   File: HttpCallFragmentPresenterTest.java   Source Code and License 5 votes vote down vote up
private void resolveBackgroundTask() {
  doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      BackgroundTask<String> backgroundTask = (BackgroundTask<String>) invocation.getArguments()[0];
      backgroundTask.onResult(backgroundTask.onExecute());
      return null;
    }
  }).when(mockExecutor).execute(any(BackgroundTask.class));
}
 
Example 48
Project: GitHub   File: DraweeMocks.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a mock GenericDraweeHierarchyBuilder that builds a new DH instance each time.
 * @return mock GenericDraweeHierarchyBuilder
 */
public static GenericDraweeHierarchyBuilder mockGenericDraweeHierarchyBuilder() {
  GenericDraweeHierarchyBuilder builder =
      mock(GenericDraweeHierarchyBuilder.class, CALLS_REAL_METHODS);
  doAnswer(
      new Answer<Object>() {
        @Override
        public DraweeHierarchy answer(InvocationOnMock invocation) throws Throwable {
          return mockDraweeHierarchy();
        }
      }).when(builder).build();
  return builder;
}
 
Example 49
Project: teasy   File: FramesTransparentWebDriverTest.java   Source Code and License 5 votes vote down vote up
private void whenFrameCalled(final WebDriver.TargetLocator targetLocator) {
    when(targetLocator.frame(any(WebElement.class))).thenAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            ((WebElement) args[0]).getTagName();
            return null;
        }
    });
}
 
Example 50
Project: GitHub   File: FragmentMvpViewStateDelegateImplTest.java   Source Code and License 5 votes vote down vote up
@Test public void appStartWithViewStateFromMemoryAndBundleShouldPreferViewStateFromMemory() {

    Mockito.doAnswer(new Answer() {
      @Override public Object answer(InvocationOnMock invocation) throws Throwable {
        viewState = Mockito.spy(new SimpleRestorableViewState());
        return viewState;
      }
    }).when(callback).createViewState();

    startFragment(null, 1, 1, 1, 1, 1, 0, null, 0, 1, 0);
    Bundle bundle = BundleMocker.create();
    finishFragment(bundle, 1, true, true, false);
    startFragment(bundle, 1, 2, 2, 1, 2, 1, true, 1, 1, 1);
    finishFragment(bundle, 1, false, false, true);
  }
 
Example 51
Project: rmq4note   File: RemoteBrokerOffsetStoreTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testReadOffset_Success() throws Exception {
    OffsetStore offsetStore = new RemoteBrokerOffsetStore(mQClientFactory, group);
    final MessageQueue messageQueue = new MessageQueue(topic, brokerName, 3);

    doAnswer(new Answer() {
        @Override public Object answer(InvocationOnMock mock) throws Throwable {
            UpdateConsumerOffsetRequestHeader updateRequestHeader = mock.getArgument(1);
            when(mqClientAPI.queryConsumerOffset(anyString(), any(QueryConsumerOffsetRequestHeader.class), anyLong())).thenReturn(updateRequestHeader.getCommitOffset());
            return null;
        }
    }).when(mqClientAPI).updateConsumerOffsetOneway(any(String.class), any(UpdateConsumerOffsetRequestHeader.class), any(Long.class));

    offsetStore.updateOffset(messageQueue, 1024, false);
    offsetStore.persist(messageQueue);
    assertThat(offsetStore.readOffset(messageQueue, ReadOffsetType.READ_FROM_STORE)).isEqualTo(1024);

    offsetStore.updateOffset(messageQueue, 1023, false);
    offsetStore.persist(messageQueue);
    assertThat(offsetStore.readOffset(messageQueue, ReadOffsetType.READ_FROM_STORE)).isEqualTo(1023);

    offsetStore.updateOffset(messageQueue, 1022, true);
    offsetStore.persist(messageQueue);
    assertThat(offsetStore.readOffset(messageQueue, ReadOffsetType.READ_FROM_STORE)).isEqualTo(1023);

    offsetStore.updateOffset(messageQueue, 1025, false);
    offsetStore.persistAll(new HashSet<>(Collections.singletonList(messageQueue)));
    assertThat(offsetStore.readOffset(messageQueue, ReadOffsetType.READ_FROM_STORE)).isEqualTo(1025);
}
 
Example 52
Project: oscm   File: UserServiceBeanTest.java   Source Code and License 5 votes vote down vote up
private static POUserAndSubscriptions initUserWithAssignments(
        final boolean suspend, UserServiceBean bean, final PlatformUser pu)
        throws Exception {
    POUserAndSubscriptions user = new POUserAndSubscriptions();
    populateUserDetails(pu, user);
    user.setAssignedRoles(EnumSet.of(UserRoleType.ORGANIZATION_ADMIN));
    user.setSubscriptions(createSubscriptions());

    when(
            bean.slsl.getSubscriptionAssignments(any(PlatformUser.class),
                    anySetOf(SubscriptionStatus.class))).thenReturn(
            createAssignments());
    when(
            Boolean.valueOf(bean.ssl.addRevokeUser(anyString(),
                    anyListOf(VOUsageLicense.class),
                    anyListOf(VOUser.class)))).thenAnswer(
            new Answer<Boolean>() {

                @Override
                @SuppressWarnings("unchecked")
                public Boolean answer(InvocationOnMock invocation)
                        throws Throwable {
                    String subId = (String) invocation.getArguments()[0];
                    List<VOUsageLicense> lics = (List<VOUsageLicense>) invocation
                            .getArguments()[1];
                    List<VOUser> users = (List<VOUser>) invocation
                            .getArguments()[2];
                    verifyAddRevokeCall(subId, lics, users, pu);
                    return Boolean.valueOf(!suspend);
                }
            });
    return user;
}
 
Example 53
Project: AndroidSnooper   File: DatabaseReaderTest.java   Source Code and License 5 votes vote down vote up
private void resolveBackgroundTask() {
  doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
      BackgroundTask<String> backgroundTask = (BackgroundTask<String>) invocation.getArguments()[0];
      backgroundTask.onResult(backgroundTask.onExecute());
      return null;
    }
  }).when(backgroundTaskExecutor).execute(any(BackgroundTask.class));
}
 
Example 54
Project: GitHub   File: RequestFutureTargetTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = ExecutionException.class)
public void testThrowsExecutionExceptionIfLoadFailsWhileWaiting()
    throws ExecutionException, InterruptedException {
  doAnswer(new Answer<Void>() {
    @Override
    public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
      future.onLoadFailed(null);
      return null;
    }
  }).when(waiter).waitForTimeout(eq(future), anyLong());
  future.get();
}
 
Example 55
Project: oscm   File: APPlatformServiceBeanIT.java   Source Code and License 5 votes vote down vote up
@Override
protected void setup(TestContainer container) throws Exception {
    container.enableInterfaceMocking(true);
    container.addBean(Mockito.mock(BesDAO.class));
    container.addBean(instanceDAO = Mockito.mock(ServiceInstanceDAO.class));
    container.addBean(
            authSvc = Mockito.mock(APPAuthenticationServiceBean.class));
    container.addBean(
            concSvc = Mockito.mock(APPConcurrencyServiceBean.class));
    container.addBean(
            configSvc = Mockito.mock(APPConfigurationServiceBean.class));
    container.addBean(
            commSvc = Mockito.mock(APPCommunicationServiceBean.class));
    container.addBean(platformSvc = spy(new APPlatformServiceBean()));
    container.get(APPlatformService.class);
    Answer<HashMap<String, String>> answer = new Answer<HashMap<String, String>>() {

        @Override
        public HashMap<String, String> answer(InvocationOnMock invocation)
                throws Throwable {
            HashMap<String, String> map = new HashMap<>();
            map.put("key", "value");
            return map;
        }
    };
    Mockito.doAnswer(answer).when(configSvc)
            .getControllerConfigurationSettings(Matchers.anyString());

    defaultUser = new VOUser();
    defaultUser.setUserId("user");
    defaultAuth = new PasswordAuthentication("user", "password");
    platformSvc.setAuthService(authSvc);
    platformSvc.setConfigService(configSvc);
    platformSvc.setConcurrencyService(concSvc);
    platformSvc.setMailService(commSvc);
    platformSvc.setInstanceDAO(instanceDAO);
}
 
Example 56
Project: db_utils   File: UncloseableConnectionTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {

    assertNotNull(conn);

    Mockito.doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            throw new IllegalAccessError();
        }
    }).when(conn).close();
}
 
Example 57
Project: oscm   File: ServiceProvisioningServiceBeanTriggerIdIT.java   Source Code and License 5 votes vote down vote up
@Override
protected void setup(TestContainer container) throws Exception {
    container.enableInterfaceMocking(true);

    TriggerQueueServiceLocal triggerQueueServiceLocal = mock(
            TriggerQueueServiceLocal.class);
    container.addBean(triggerQueueServiceLocal);
    container.addBean(new ConfigurationServiceStub());
    container.addBean(new DataServiceBean());
    container.addBean(new ServiceProvisioningServiceBean());

    svcProv = container.get(ServiceProvisioningService.class);
    mgr = container.get(DataService.class);

    // Initialize the test setup data.
    initData();

    // mock the answer of the trigger queue
    doAnswer(new Answer<List<TriggerProcessMessageData>>() {
        @Override
        public List<TriggerProcessMessageData> answer(
                InvocationOnMock invocation) throws Throwable {
            return Collections.singletonList(triggerProcessData);
        }
    }).when(triggerQueueServiceLocal)
            .sendSuspendingMessages(anyListOf(TriggerMessage.class));

}
 
Example 58
Project: GitHub   File: EnumRuleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void applyGeneratesUniqueEnumNamesForMultipleEnumNodesWithSameName() {

    Answer<String> firstArgAnswer = new FirstArgAnswer<String>();
    when(nameHelper.getFieldName(anyString(), Matchers.any(JsonNode.class))).thenAnswer(firstArgAnswer);
    when(nameHelper.replaceIllegalCharacters(anyString())).thenAnswer(firstArgAnswer);
    when(nameHelper.normalizeName(anyString())).thenAnswer(firstArgAnswer);

    JPackage jpackage = new JCodeModel()._package(getClass().getPackage().getName());

    ObjectMapper objectMapper = new ObjectMapper();
    ArrayNode arrayNode = objectMapper.createArrayNode();
    arrayNode.add("open");
    arrayNode.add("closed");
    ObjectNode enumNode = objectMapper.createObjectNode();
    enumNode.put("type", "string");
    enumNode.set("enum", arrayNode);

    // We're always a string for the purposes of this test
    when(typeRule.apply("status", enumNode, jpackage, schema))
    .thenReturn(jpackage.owner()._ref(String.class));

    JType result1 = rule.apply("status", enumNode, jpackage, schema);
    JType result2 = rule.apply("status", enumNode, jpackage, schema);

    assertThat(result1.fullName(), is("org.jsonschema2pojo.rules.Status"));
    assertThat(result2.fullName(), is("org.jsonschema2pojo.rules.Status_"));
}
 
Example 59
Project: GitHub   File: FragmentMvpViewStateDelegateImplTest.java   Source Code and License 5 votes vote down vote up
@Test public void appStartAfterProcessDeathAndViewStateRecreationFromBundle() {
  Mockito.doAnswer(new Answer() {
    @Override public Object answer(InvocationOnMock invocation) throws Throwable {
      viewState = Mockito.spy(new SimpleRestorableViewState());
      return viewState;
    }
  }).when(callback).createViewState();

  Bundle bundle = BundleMocker.create();
  bundle.putString(FragmentMvpViewStateDelegateImpl.KEY_MOSBY_VIEW_ID, "123456789");

  startFragment(bundle, 1, 1, 1, 1, 1, 1, false, 1, 0, 1);
}
 
Example 60
Project: ZooKeeper   File: WatchLeakTest.java   Source Code and License 5 votes vote down vote up
/**
 * Mock a client channel with a connection request and a watches message
 * inside.
 * 
 * @return a socket channel
 * @throws IOException
 */
private SocketChannel createClientSocketChannel() throws IOException {

    SocketChannel socketChannel = mock(SocketChannel.class);
    Socket socket = mock(Socket.class);
    InetSocketAddress socketAddress = new InetSocketAddress(1234);
    when(socket.getRemoteSocketAddress()).thenReturn(socketAddress);
    when(socketChannel.socket()).thenReturn(socket);

    // Send watches packet to server connection
    final ByteBuffer connRequest = createConnRequest();
    final ByteBuffer watchesMessage = createWatchesMessage();
    final ByteBuffer request = ByteBuffer.allocate(connRequest.limit()
            + watchesMessage.limit());
    request.put(connRequest);
    request.put(watchesMessage);

    Answer<Integer> answer = new Answer<Integer>() {
        int i = 0;

        @Override
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            Object[] args = invocation.getArguments();
            ByteBuffer bb = (ByteBuffer) args[0];
            for (int k = 0; k < bb.limit(); k++) {
                bb.put(request.get(i));
                i = i + 1;
            }
            return bb.limit();
        }
    };
    when(socketChannel.read(any(ByteBuffer.class))).thenAnswer(answer);
    return socketChannel;
}