org.mockito.ArgumentMatcher Java Examples

The following examples show how to use org.mockito.ArgumentMatcher. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestUtils.java    From ShedLock with Apache License 2.0 6 votes vote down vote up
public static LockConfiguration hasParams(String name, long lockAtMostFor, long lockAtLeastFor) {
    return argThat(new ArgumentMatcher<LockConfiguration>() {
        @Override
        public boolean matches(LockConfiguration c) {
            return name.equals(c.getName())
                && isNearTo(lockAtMostFor, c.getLockAtMostUntil())
                && isNearTo(lockAtLeastFor, c.getLockAtLeastUntil());
        }

        @Override
        public String toString() {
            Instant now = ClockProvider.now();
            return "hasParams(\"" + name + "\", " + now.plusMillis(lockAtMostFor) + ", " + now.plusMillis(lockAtLeastFor) + ")";
        }
    });
}
 
Example #2
Source File: DocumentRetrieverTest.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendSingleMessage() throws DocumentRetrieverException {
    ClientParameters params = createParameters()
            .setDocumentIds(asIterator(DOC_ID_1))
            .setPriority(DocumentProtocol.Priority.HIGH_1)
            .setNoRetry(true)
            .setLoadTypeName("loadtype")
            .build();

    when(mockedSession.syncSend(any())).thenReturn(createDocumentReply(DOC_ID_1));

    LoadTypeSet loadTypeSet = new LoadTypeSet();
    loadTypeSet.addLoadType(1, "loadtype", DocumentProtocol.Priority.HIGH_1);
    DocumentRetriever documentRetriever = new DocumentRetriever(
            new ClusterList(),
            mockedFactory,
            loadTypeSet,
            params);
    documentRetriever.retrieveDocuments();

    verify(mockedSession, times(1)).syncSend(argThat((ArgumentMatcher<GetDocumentMessage>) o ->
            o.getPriority().equals(DocumentProtocol.Priority.HIGH_1) &&
            !o.getRetryEnabled() &&
            o.getLoadType().equals(new LoadType(1, "loadtype", DocumentProtocol.Priority.HIGH_1))));
    assertContainsDocument(DOC_ID_1);
}
 
Example #3
Source File: MAsyncTaskTest.java    From mobile-messaging-sdk-android with Apache License 2.0 6 votes vote down vote up
@NonNull
private Throwable eqBackendError(final Class<? extends BackendBaseException> cls, final ApiIOException innerException, final Object content) {
    return argThat(new ArgumentMatcher<Throwable>() {
        @Override
        public boolean matches(Object argument) {
            if (!cls.isInstance(argument)) {
                return false;
            }

            BackendBaseException exception = (BackendBaseException) argument;
            if (!(exception.getCause() instanceof ApiIOException)) {
                return false;
            }

            ApiIOException ioException = (ApiIOException) exception.getCause();
            boolean isIoExceptionTheSameAsInnerException = ioException.toString().equals(innerException.toString());
            if (!(argument instanceof BackendCommunicationExceptionWithContent) || content == null) {
                return isIoExceptionTheSameAsInnerException;
            }

            BackendCommunicationExceptionWithContent exceptionWithContent = (BackendCommunicationExceptionWithContent) argument;
            return isIoExceptionTheSameAsInnerException && exceptionWithContent.getContent().equals(content);
        }
    });
}
 
Example #4
Source File: GetNewBlockTest.java    From teku with Apache License 2.0 6 votes vote down vote up
@Test
void shouldPropagateChainDataUnavailableExceptionToGlobalExceptionHandlerWithGraffiti()
    throws Exception {
  final Map<String, List<String>> params =
      Map.of(
          RestApiConstants.SLOT,
          List.of("1"),
          RANDAO_REVEAL,
          List.of(signature.toHexString()),
          RestApiConstants.GRAFFITI,
          List.of(graffiti.toHexString()));
  when(context.queryParamMap()).thenReturn(params);
  when(provider.getUnsignedBeaconBlockAtSlot(ONE, signature, Optional.of(graffiti)))
      .thenReturn(SafeFuture.failedFuture(new ChainDataUnavailableException()));
  handler.handle(context);

  // Exception should just be propagated up via the future
  verify(context, never()).status(anyInt());
  verify(context)
      .result(
          argThat((ArgumentMatcher<SafeFuture<?>>) CompletableFuture::isCompletedExceptionally));
}
 
Example #5
Source File: ClusterHintsPollerTest.java    From emodb with Apache License 2.0 6 votes vote down vote up
private ArgumentMatcher<Statement> getHostStatementMatcher(final Host host, final String query)
        throws Exception {
    return new ArgumentMatcher<Statement>() {
        @Override
        public boolean matches(Object argument) {
            SelectedHostStatement statement = (SelectedHostStatement) argument;

            return ((SimpleStatement)statement.getStatement()).getQueryString().equals(query) &&
                    Objects.equals(statement.getHostCordinator().getAddress(), host.getAddress());
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(format("query:%s host:%s", query, host.getAddress().toString()));
        }
    };
}
 
Example #6
Source File: MXBeanPollerTest.java    From swage with Apache License 2.0 6 votes vote down vote up
@Test
public void senses() throws Exception {
    final MetricRecorder recorder = new NullRecorder();

    final Sensor sensor1 = mock(Sensor.class);
    final Sensor sensor2 = mock(Sensor.class);
    when(sensor1.addContext(any(TypedMap.class))).then(invocation -> invocation.getArgument(0));
    when(sensor2.addContext(any(TypedMap.class))).then(invocation -> invocation.getArgument(0));

    List<Sensor> sensors = new ArrayList<>();
    sensors.add(sensor1);
    sensors.add(sensor2);

    MXBeanPoller poller = new MXBeanPoller(recorder, 1, sensors);
    Thread.sleep(1500); // wait for a poll to occur
    poller.shutdown();

    final ArgumentMatcher<TypedMap> dataMatch = new DataMatcher();
    verify(sensor1).addContext(argThat(dataMatch));
    verify(sensor2).addContext(argThat(dataMatch));
    verify(sensor1, atLeastOnce()).sense(any(MetricContext.class));
    verify(sensor2, atLeastOnce()).sense(any(MetricContext.class));
}
 
Example #7
Source File: CloudFoundryAppDeployerTest.java    From spring-cloud-app-broker with Apache License 2.0 6 votes vote down vote up
private ArgumentMatcher<PushApplicationManifestRequest> matchesManifest(ApplicationManifest expectedManifest) {
	return new ArgumentMatcher<PushApplicationManifestRequest>() {
		@Override
		public boolean matches(PushApplicationManifestRequest request) {
			if (request.getManifests().size() == EXPECTED_MANIFESTS) {
				return request.getManifests().get(0).equals(expectedManifest);
			}

			return false;
		}

		@Override
		public String toString() {
			return expectedManifest.toString();
		}
	};
}
 
Example #8
Source File: ShardInstanceTest.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@Test
public void blobsAreMissingWhenWorkersAreEmpty() throws Exception {
  String workerName = "worker";
  when(mockInstanceLoader.load(eq(workerName))).thenReturn(mockWorkerInstance);

  ImmutableSet<String> workers = ImmutableSet.of(workerName);
  when(mockBackplane.getWorkers()).thenReturn(workers);

  Digest digest = Digest.newBuilder().setHash("hash").setSizeBytes(1).build();
  List<Digest> queryDigests = ImmutableList.of(digest);
  ArgumentMatcher<Iterable<Digest>> queryMatcher =
      (digests) -> Iterables.elementsEqual(digests, queryDigests);
  when(mockWorkerInstance.findMissingBlobs(
          argThat(queryMatcher), any(Executor.class), any(RequestMetadata.class)))
      .thenReturn(immediateFuture(queryDigests));
  Iterable<Digest> missingDigests =
      instance
          .findMissingBlobs(
              queryDigests, newDirectExecutorService(), RequestMetadata.getDefaultInstance())
          .get();
  verify(mockWorkerInstance, times(1))
      .findMissingBlobs(argThat(queryMatcher), any(Executor.class), any(RequestMetadata.class));
  assertThat(missingDigests).containsExactly(digest);
}
 
Example #9
Source File: ReadSpannerSchemaTest.java    From beam with Apache License 2.0 6 votes vote down vote up
private void preparePkMetadata(ReadOnlyTransaction tx, List<Struct> rows) {
  Type type =
      Type.struct(
          Type.StructField.of("table_name", Type.string()),
          Type.StructField.of("column_name", Type.string()),
          Type.StructField.of("column_ordering", Type.string()));
  when(tx.executeQuery(
          argThat(
              new ArgumentMatcher<Statement>() {

                @Override
                public boolean matches(Statement argument) {
                  if (!(argument instanceof Statement)) {
                    return false;
                  }
                  Statement st = (Statement) argument;
                  return st.getSql().contains("information_schema.index_columns");
                }
              })))
      .thenReturn(ResultSets.forRows(type, rows));
}
 
Example #10
Source File: SessionWindowAssignerTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testMergeCoveringWindow() {
	MergingWindowAssigner.MergeCallback callback = mock(MergingWindowAssigner.MergeCallback.class);
	SessionWindowAssigner assigner = SessionWindowAssigner.withGap(Duration.ofMillis(5000));

	TreeSet<TimeWindow> sortedWindows = new TreeSet<>();
	sortedWindows.addAll(Arrays.asList(
			new TimeWindow(1, 4),
			new TimeWindow(5, 7),
			new TimeWindow(9, 10)));
	assigner.mergeWindows(new TimeWindow(3, 6), sortedWindows, callback);

	verify(callback, times(1)).merge(
			eq(new TimeWindow(1, 7)),
			argThat((ArgumentMatcher<Collection<TimeWindow>>) timeWindows ->
					containsInAnyOrder(
							new TimeWindow(1, 4),
							new TimeWindow(5, 7),
							new TimeWindow(3, 6)).matches(timeWindows)));
}
 
Example #11
Source File: SessionWindowAssignerTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testMergeConsecutiveWindows() {
	MergingWindowAssigner.MergeCallback callback = mock(MergingWindowAssigner.MergeCallback.class);
	SessionWindowAssigner assigner = SessionWindowAssigner.withGap(Duration.ofMillis(5000));

	TreeSet<TimeWindow> sortedWindows = new TreeSet<>();
	sortedWindows.addAll(Arrays.asList(
			new TimeWindow(0, 1),
			new TimeWindow(2, 3),
			new TimeWindow(4, 5),
			new TimeWindow(7, 8)));
	assigner.mergeWindows(new TimeWindow(1, 2), sortedWindows, callback);

	verify(callback, times(1)).merge(
			eq(new TimeWindow(0, 3)),
			argThat((ArgumentMatcher<Collection<TimeWindow>>) timeWindows ->
					containsInAnyOrder(
							new TimeWindow(0, 1),
							new TimeWindow(1, 2),
							new TimeWindow(2, 3)).matches(timeWindows)));
}
 
Example #12
Source File: SubscriptionServiceTest.java    From cerebro with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void updateSubscriptionEnableAlarm() throws Exception {
    // ****
    // Init, set repo to return a fully disabled alarm
    Alarm disabledAlarm = TestUtils.getDefaultAlarm();
    disabledAlarm.getSubscriptions().get(0).setEnabled(false);
    when(seyrenRepository.getAlarm(TestUtils.DEFAULT_ALARM_ID)).thenReturn(disabledAlarm);
    // ****

    Alarm alarm = TestUtils.getDefaultAlarm();
    Subscription subscription = alarm.getSubscriptions().get(0);
    subscription.setEnabled(true);

    subscriptionService.updateSubscription(subscription, TestUtils.DEFAULT_ALARM_ID);

    verify(seyrenRepository).updateSubscription(subscription, TestUtils.DEFAULT_ALARM_ID);
    verify(seyrenRepository).updateAlarm(argThat(new ArgumentMatcher<Alarm>() {
        @Override
        public boolean matches(Object argument) {
            Alarm argAlarm = (Alarm) argument;
            return argAlarm.getId().equals(alarm.getId()) && argAlarm.isEnabled();
        }
    }));
}
 
Example #13
Source File: ChainingPrincipalResolverTest.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolve() throws Exception {
    final Credential credential = mock(Credential.class);
    when(credential.getId()).thenReturn("input");

    final PrincipalResolver resolver1 = mock(PrincipalResolver.class);
    when(resolver1.supports(eq(credential))).thenReturn(true);
    when(resolver1.resolve((eq(credential)))).thenReturn(new SimplePrincipal("output"));

    final PrincipalResolver resolver2 = mock(PrincipalResolver.class);
    when(resolver2.supports(any(Credential.class))).thenReturn(false);
    when(resolver2.resolve(argThat(new ArgumentMatcher<Credential>() {
        @Override
        public boolean matches(final Object o) {
            return ((Credential) o).getId().equals("output");
        }
    }))).thenReturn(
            new SimplePrincipal("final", Collections.<String, Object>singletonMap("mail", "[email protected]")));

    final ChainingPrincipalResolver resolver = new ChainingPrincipalResolver();
    resolver.setChain(Arrays.asList(resolver1, resolver2));
    final Principal principal = resolver.resolve(credential);
    assertEquals("final", principal.getId());
    assertEquals("[email protected]", principal.getAttributes().get("mail"));
}
 
Example #14
Source File: AdminUserCreatorTest.java    From codenvy with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void shouldCreateAdminUser() throws Exception {
  Injector injector = Guice.createInjector(new OrgModule());
  UserManager userManager = injector.getInstance(UserManager.class);
  when(userManager.getByName(NAME)).thenThrow(new NotFoundException("nfex"));
  when(userManager.create(any(UserImpl.class), anyBoolean())).thenReturn(user);
  injector.getInstance(AdminUserCreator.class);

  verify(userManager).getByName(NAME);
  verify(userManager).create(new UserImpl(NAME, EMAIL, NAME, PASSWORD, emptyList()), false);
  verify(permissionsManager)
      .storePermission(
          argThat(
              (ArgumentMatcher<SystemPermissionsImpl>)
                  argument -> argument.getUserId().equals("qwe")));
}
 
Example #15
Source File: ReadSpannerSchemaTest.java    From beam with Apache License 2.0 6 votes vote down vote up
private void prepareColumnMetadata(ReadOnlyTransaction tx, List<Struct> rows) {
  Type type =
      Type.struct(
          Type.StructField.of("table_name", Type.string()),
          Type.StructField.of("column_name", Type.string()),
          Type.StructField.of("spanner_type", Type.string()),
          Type.StructField.of("cells_mutated", Type.int64()));
  when(tx.executeQuery(
          argThat(
              new ArgumentMatcher<Statement>() {

                @Override
                public boolean matches(Statement argument) {
                  if (!(argument instanceof Statement)) {
                    return false;
                  }
                  Statement st = (Statement) argument;
                  return st.getSql().contains("information_schema.columns");
                }
              })))
      .thenReturn(ResultSets.forRows(type, rows));
}
 
Example #16
Source File: ReadOnlyServiceTest.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddRequest() throws Exception {
    final byte[] requestContext = TestUtils.getRandomBytes();
    this.readOnlyServiceImpl.addRequest(requestContext, new ReadIndexClosure() {

        @Override
        public void run(final Status status, final long index, final byte[] reqCtx) {

        }
    });
    this.readOnlyServiceImpl.flush();
    Mockito.verify(this.node).handleReadIndexRequest(Mockito.argThat(new ArgumentMatcher<ReadIndexRequest>() {

        @Override
        public boolean matches(final Object argument) {
            if (argument instanceof ReadIndexRequest) {
                final ReadIndexRequest req = (ReadIndexRequest) argument;
                return req.getGroupId().equals("test") && req.getServerId().equals("localhost:8081:0")
                       && req.getEntriesCount() == 1
                       && Arrays.equals(requestContext, req.getEntries(0).toByteArray());
            }
            return false;
        }

    }), Mockito.any());
}
 
Example #17
Source File: DatabaseStepsTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void shouldCompareQueriesAndUseAllColumnValuesIfUserDoesntSpecifyKeys() throws InterruptedException,
    ExecutionException, TimeoutException, SQLException
{
    mockDataSource(QUERY, DB_KEY, mockResultSet(COL1, VAL1, COL2, null, COL3, VAL3));
    mockDataSource(QUERY, DB_KEY2, mockResultSet(COL1, VAL1, COL2, null, COL3, VAL3));
    when(softAssert.assertTrue(QUERY_RESULTS_ARE_EQUAL, true)).thenReturn(true);
    ArgumentMatcher<CharSequence> matcher = s ->
    {
        String toHash = s.toString();
        return toHash.contains(VAL1) && toHash.contains(VAL3) && !toHash.contains(VAL2);
    };
    when(hashFunction.hashString(argThat(matcher), eq(StandardCharsets.UTF_8))).thenReturn(HASH1);
    configureTimeout();
    mockRowsFilterAsNOOP();
    databaseSteps.compareData(QUERY, DB_KEY, QUERY, DB_KEY2, Set.of());
    verify(attachmentPublisher).publishAttachment(eq(QUERIES_STATISTICS_FTL),
            any(Map.class), eq(QUERIES_STATISTICS));
    verify(hashFunction, times(2)).hashString(argThat(matcher), eq(StandardCharsets.UTF_8));
}
 
Example #18
Source File: AdminUserCreatorTest.java    From codenvy with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void shouldAddSystemPermissionsInLdapMode() throws Exception {
  Injector injector = Guice.createInjector(new LdapModule());
  UserManager userManager = injector.getInstance(UserManager.class);
  when(userManager.getByName(nullable(String.class))).thenReturn(user);
  when(userManager.create(any(UserImpl.class), anyBoolean())).thenReturn(user);
  AdminUserCreator creator = injector.getInstance(AdminUserCreator.class);
  creator.onEvent(
      new PostUserPersistedEvent(new UserImpl(NAME, EMAIL, NAME, PASSWORD, emptyList())));
  verify(permissionsManager)
      .storePermission(
          argThat(
              (ArgumentMatcher<SystemPermissionsImpl>)
                  argument -> argument.getUserId().equals(NAME)));
}
 
Example #19
Source File: Helper.java    From android-nmea-parser with MIT License 5 votes vote down vote up
public static ArgumentMatcher<Double> roughlyEq(final double expected, final double delta) {
    return new ArgumentMatcher<Double>() {
        @Override
        public boolean matches(Object argument) {
            return Math.abs(expected - (Double) argument) <= delta;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(Double.toString(expected) + "±" + Double.toString(delta));
        }
    };
}
 
Example #20
Source File: NucleusFragmentTest.java    From FlowGeek with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCreation() throws Exception {
    tested.onCreate(null);
    assertEquals(mockPresenter, tested.getPresenter());
    PowerMockito.verifyStatic(times(1));
    ReflectionPresenterFactory.fromViewClass(argThat(new ArgumentMatcher<Class<?>>() {
        @Override
        public boolean matches(Object argument) {
            return TestView.class.isAssignableFrom((Class)argument);
        }
    }));
    verify(mockDelegate, times(1)).getPresenter();
    verifyNoMoreInteractions(mockPresenter, mockDelegate, mockFactory);
}
 
Example #21
Source File: MobileMessageHandlerTest.java    From mobile-messaging-sdk-android with Apache License 2.0 5 votes vote down vote up
private Message messageWith(final String messageId) {
    return argThat(new ArgumentMatcher<Message>() {
        @Override
        public boolean matches(Object o) {
            return messageId.equals(((Message) o).getMessageId());
        }
    });
}
 
Example #22
Source File: Helper.java    From android-nmea-parser with MIT License 5 votes vote down vote up
public static ArgumentMatcher<Float> roughlyEq(final float expected, final float delta) {
    return new ArgumentMatcher<Float>() {
        @Override
        public boolean matches(Object argument) {
            return Math.abs(expected - (Float) argument) <= delta;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText(Float.toString(expected) + "±" + Float.toString(delta));
        }
    };
}
 
Example #23
Source File: KafkaSubscriberTest.java    From ja-micro with Apache License 2.0 5 votes vote down vote up
@Test
public void subscriberLosesPartitionAssignment() {
    KafkaSubscriber<String> subscriber = new KafkaSubscriber<>(new MessageCallback(),
            "topic", "groupId", false,
            KafkaSubscriber.OffsetReset.Earliest, 1, 1, 1,
            5000, 5000, KafkaSubscriber.QueueType.OffsetBlocking, 1000);
    KafkaTopicInfo message1 = new KafkaTopicInfo("topic", 0, 1, null);
    KafkaTopicInfo message2 = new KafkaTopicInfo("topic", 0, 2, null);
    KafkaTopicInfo message3 = new KafkaTopicInfo("topic", 1, 1, null);
    KafkaTopicInfo message4 = new KafkaTopicInfo("topic", 1, 2, null);
    subscriber.consume(message1);
    subscriber.consume(message2);
    subscriber.consume(message3);
    subscriber.consume(message4);
    KafkaConsumer realConsumer = mock(KafkaConsumer.class);
    class ArgMatcher implements ArgumentMatcher<Map<TopicPartition, OffsetAndMetadata>> {
        @Override
        public boolean matches(Map<TopicPartition, OffsetAndMetadata> arg) {
            OffsetAndMetadata oam = arg.values().iterator().next();
            return oam.offset() == 3;
        }
    }
    doThrow(new CommitFailedException()).when(realConsumer).commitSync(argThat(new ArgMatcher()));
    subscriber.realConsumer = realConsumer;
    subscriber.offsetCommitter = new OffsetCommitter(realConsumer, Clock.systemUTC());
    subscriber.consumeMessages();
}
 
Example #24
Source File: MobileMessagingCloudServiceTest.java    From mobile-messaging-sdk-android with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private static Intent intentWith(final String senderId, final String token) {
    return Mockito.argThat(new ArgumentMatcher<Intent>() {
        @Override
        public boolean matches(Object o) {
            Intent intent = (Intent) o;
            return senderId.equals(intent.getStringExtra(MobileMessagingCloudHandler.EXTRA_SENDER_ID))
                    && token.equals(intent.getStringExtra(MobileMessagingCloudHandler.EXTRA_TOKEN));
        }
    });
}
 
Example #25
Source File: SelectedClassResolverFromClasspathTest.java    From ArchUnit with Apache License 2.0 5 votes vote down vote up
private URI uriFor(final Class<?> clazz) {
    return argThat(new ArgumentMatcher<URI>() {
        @Override
        public boolean matches(URI argument) {
            return argument.toString().contains(clazz.getSimpleName());
        }
    });
}
 
Example #26
Source File: SmartTestingProviderTest.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
@Test
public void test_when_invoke_is_called_with_whole_set_of_classes() throws Exception {
    // given
    SmartTestingSurefireProvider provider = new SmartTestingSurefireProvider(providerParameters, providerFactory);

    // when
    provider.invoke(new TestsToRun(expectedClassesToRun));

    // then
    verify(surefireProvider, times(0)).getSuites();
    verify(surefireProvider, times(1)).invoke(argThat((ArgumentMatcher<Iterable<Class>>)
        iterable -> iterableContains(iterable, expectedClassesToRun)));
}
 
Example #27
Source File: SmartTestingProviderTest.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
@Test
public void test_when_invoke_is_called_with_one_class() throws Exception {
    // given
    SmartTestingSurefireProvider provider = new SmartTestingSurefireProvider(providerParameters, providerFactory);

    // when
    provider.invoke(ATest.class);

    // then
    verify(surefireProvider, times(0)).getSuites();
    verify(surefireProvider, times(1)).invoke(argThat((ArgumentMatcher<Iterable<Class>>)
        iterable -> iterableContains(iterable, new LinkedHashSet(Collections.singletonList(ATest.class)))));
}
 
Example #28
Source File: MobileMessagingCloudServiceTest.java    From mobile-messaging-sdk-android with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private static Intent intentWith(final String senderId) {
    return Mockito.argThat(new ArgumentMatcher<Intent>() {
        @Override
        public boolean matches(Object o) {
            Intent intent = (Intent) o;
            return senderId.equals(intent.getStringExtra(MobileMessagingCloudHandler.EXTRA_SENDER_ID));
        }
    });
}
 
Example #29
Source File: NucleusLayoutTest.java    From FlowGeek with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCreation() throws Exception {
    assertEquals(mockPresenter, tested.getPresenter());
    PowerMockito.verifyStatic(times(1));
    ReflectionPresenterFactory.fromViewClass(argThat(new ArgumentMatcher<Class<?>>() {
        @Override
        public boolean matches(Object argument) {
            return TestView.class.isAssignableFrom((Class)argument);
        }
    }));
    verify(mockDelegate, times(1)).getPresenter();
    verifyNoMoreInteractions(mockPresenter, mockDelegate, mockFactory);
}
 
Example #30
Source File: IntegrationDeploymentHandlerTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetVersionTo1ForInitialUpdate() {
    final SecurityContext security = mock(SecurityContext.class);
    final Principal principal = mock(Principal.class);
    when(security.getUserPrincipal()).thenReturn(principal);
    when(principal.getName()).thenReturn("user");

    final Integration integration = new Integration.Builder().build();
    when(dataManager.fetch(Integration.class, INTEGRATION_ID)).thenReturn(integration);
    Map<String, String> labels = new HashMap<>();
    List<DeploymentConfig> emptyList = new ArrayList<>();
    when(openShiftService.getDeploymentsByLabel(labels)).thenReturn(emptyList);
    when(dataManager.fetchAllByPropertyValue(IntegrationDeployment.class, "integrationId", INTEGRATION_ID))
        .thenReturn(Stream.empty());

    handler.update(security, INTEGRATION_ID);

    final IntegrationDeployment expected = new IntegrationDeployment.Builder().id(compositeId(INTEGRATION_ID, 1))
        .spec(integration).version(1).userId("user").build();

    verify(dataManager).create(argThat(new ArgumentMatcher<IntegrationDeployment>() {
        @Override
        public boolean matches(IntegrationDeployment given) {
            return expected.builder()
                .createdAt(given.getCreatedAt()) // ignore created at and
                .updatedAt(given.getUpdatedAt()) // updated at
                .build()
            .equals(given);
        }
    }));
}