org.mockito.Captor Java Examples

The following examples show how to use org.mockito.Captor. 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: UnhandledFeature.java    From actor4j-core with Apache License 2.0 5 votes vote down vote up
@Test(timeout=5000)
public void test() {
	CountDownLatch testDone = new CountDownLatch(1);
	
	UUID dest = system.addActor(new ActorFactory() { 
		@Override
		public Actor create() {
			return new Actor("UnhandledFeatureActor") {
				@Mock
				protected Appender mockAppender;
				@Captor
				protected ArgumentCaptor<LoggingEvent> captorLoggingEvent;
				
				@Override
				public void receive(ActorMessage<?> message) {
					MockitoAnnotations.initMocks(this);
					logger().removeAllAppenders();
					logger().addAppender(mockAppender);
					unhandled(message);
					verify(mockAppender, times(1)).doAppend(captorLoggingEvent.capture());
					LoggingEvent loggingEvent = captorLoggingEvent.getValue();
					assertTrue(loggingEvent.getMessage().toString().contains("Unhandled message"));
					testDone.countDown();
				}
			};
		}
	});
	
	system.send(new ActorMessage<Object>(null, 0, system.SYSTEM_ID, dest));
	system.start();
	try {
		testDone.await();
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	system.shutdown(true);
}
 
Example #2
Source File: DefaultAnnotationEngine.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
public Object createMockFor(Annotation annotation, Field field) {
    if (annotation instanceof Mock) {
        return processAnnotationOn((Mock) annotation, field);
    }
    if (annotation instanceof MockitoAnnotations.Mock) {
        return processAnnotationOn((MockitoAnnotations.Mock) annotation, field);
    }
    if (annotation instanceof Captor) {
        return processAnnotationOn((Captor) annotation, field);
    }        

    return null;
}
 
Example #3
Source File: DefaultAnnotationEngine.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
private Object processAnnotationOn(Captor annotation, Field field) {
    Class<?> type = field.getType();
    if (!ArgumentCaptor.class.isAssignableFrom(type)) {
        throw new MockitoException("@Captor field must be of the type ArgumentCaptor.\n" + "Field: '"
                + field.getName() + "' has wrong type\n"
                + "For info how to use @Captor annotations see examples in javadoc for MockitoAnnotations class.");
    }
    Class cls = new GenericMaster().getGenericType(field);        
    return ArgumentCaptor.forClass(cls);    
}
 
Example #4
Source File: CaptorAnnotationProcessor.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
public Object process(Captor annotation, Field field) {
    Class<?> type = field.getType();
    if (!ArgumentCaptor.class.isAssignableFrom(type)) {
        throw new MockitoException("@Captor field must be of the type ArgumentCaptor.\n" + "Field: '"
           + field.getName() + "' has wrong type\n"
           + "For info how to use @Captor annotations see examples in javadoc for MockitoAnnotations class.");
    }
    Class cls = new GenericMaster().getGenericType(field);
    return ArgumentCaptor.forClass(cls);
}
 
Example #5
Source File: InjectMocksScanner.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Scan fields annotated by &#064;InjectMocks
 *
 * @return Fields that depends on Mock
 */
private Set<Field> scan() {
    Set<Field> mockDependentFields = new HashSet<Field>();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        if (null != field.getAnnotation(InjectMocks.class)) {
            assertNoAnnotations(field, Mock.class, MockitoAnnotations.Mock.class, Captor.class);
            mockDependentFields.add(field);
        }
    }

    return mockDependentFields;
}
 
Example #6
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowCaptorAndSpy() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @Spy @Captor ArgumentCaptor captor;
    });
}
 
Example #7
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowCaptorAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Captor ArgumentCaptor captor;
    });
}
 
Example #8
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowCaptorAndSpy() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @Spy @Captor ArgumentCaptor captor;
    });
}
 
Example #9
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowCaptorAndMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @Mock @Captor ArgumentCaptor captor;
    });
}
 
Example #10
Source File: DefaultAnnotationEngine.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public DefaultAnnotationEngine() {
    registerAnnotationProcessor(Mock.class, new MockAnnotationProcessor());
    registerAnnotationProcessor(MockitoAnnotations.Mock.class, new MockitoAnnotationsMockAnnotationProcessor());
    registerAnnotationProcessor(Captor.class, new CaptorAnnotationProcessor());
}
 
Example #11
Source File: MockitoBeforeTestNGMethod.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
private void initializeCaptors(Object instance) {
    List<InstanceField> instanceFields = Fields.allDeclaredFieldsOf(instance).filter(annotatedBy(Captor.class)).instanceFields();
    for (InstanceField instanceField : instanceFields) {
        instanceField.set(new CaptorAnnotationProcessor().process(instanceField.annotation(Captor.class), instanceField.jdkField()));
    }
}
 
Example #12
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowCaptorAndInjectMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @InjectMocks @Captor ArgumentCaptor captor;
    });
}
 
Example #13
Source File: Expect.java    From dcos-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that a pod was launched with exactly the provided task names over the last N accept calls. If the last
 * offer cycle had multiple offers from different agents, then separate accept calls are made on a per-agent basis.
 */
public static Expect launchedTasks(int acceptsToCheck, Collection<String> taskNames) {
  return new Expect() {
    // Use this form instead of using ArgumentCaptor.forClass() to avoid problems with typecasting generics:
    @Captor
    private ArgumentCaptor<Collection<Protos.OfferID>> offerIdsCaptor;

    @Captor
    private ArgumentCaptor<Collection<Protos.Offer.Operation>> operationsCaptor;

    @Override
    public void expect(ClusterState state, SchedulerDriver mockDriver) {
      MockitoAnnotations.initMocks(this);

      // Get the params from the last N accept calls:
      Mockito.verify(mockDriver, Mockito.atLeast(acceptsToCheck))
          .acceptOffers(offerIdsCaptor.capture(), operationsCaptor.capture(), any());
      // With the above retrieval, we will have >=acceptsToCheck calls in forward chronological order.
      // We need to manually cut that down to just the LAST acceptsToCheck calls:
      List<Collection<Protos.OfferID>> allOfferIdAcceptCalls = offerIdsCaptor.getAllValues();
      Collection<String> acceptedOfferIds = allOfferIdAcceptCalls
          .subList(allOfferIdAcceptCalls.size() - acceptsToCheck, allOfferIdAcceptCalls.size())
          .stream()
          .flatMap(Collection::stream)
          .map(Protos.OfferID::getValue)
          .collect(Collectors.toList());

      List<Collection<Protos.Offer.Operation>> allOperationAcceptCalls = operationsCaptor.getAllValues();
      List<Collection<Protos.Offer.Operation>> selectedOperationAcceptCalls = allOperationAcceptCalls
          .subList(allOperationAcceptCalls.size() - acceptsToCheck, allOperationAcceptCalls.size());

      // As a sanity check, verify that the accepted ids were all from the most recent offer cycle. This
      // ensures that we aren't looking at accepted offers from a prior offer cycle.
      Set<String> lastCycleOfferIds = state.getLastOfferCycle().stream()
          .map(o -> o.getId().getValue())
          .collect(Collectors.toSet());
      Assert.assertTrue(String.format(
          "Expected last accepted offer in last offer cycle: %s, but last %d accepted %s %s",
          lastCycleOfferIds,
          acceptsToCheck,
          acceptsToCheck == 1 ? "offer was" : "offers were",
          acceptedOfferIds),
          lastCycleOfferIds.containsAll(acceptedOfferIds));

      // Check (and capture) task launch operations:
      Collection<String> launchedTaskNames = new ArrayList<>();
      // Iterate over acceptOffers() calls, one per agent:
      for (Collection<Protos.Offer.Operation> acceptCallOperations : selectedOperationAcceptCalls) {
        // A single acceptOffers() call may contain multiple LAUNCH_GROUP operations.
        // We want to ensure they're all counted as a unit when tallying the pod.
        // TODO(nickbp): DCOS-37508 We currently produce multiple LAUNCH_GROUPs (each with identical copies
        // of the same ExecutorInfo) when launching multiple tasks in a pod. As a temporary measure, this
        // de-dupes executors by their ExecutorID. Remove this de-dupe once DCOS-37508 is fixed.
        Map<String, Protos.ExecutorInfo> executorsById = new HashMap<>();
        Collection<Protos.TaskInfo> launchedTaskInfos = new ArrayList<>();
        Collection<Protos.Resource> reservedResources = new ArrayList<>();
        for (Protos.Offer.Operation operation : acceptCallOperations) {
          switch (operation.getType()) {
            case LAUNCH_GROUP: {
              Protos.ExecutorInfo executor = operation.getLaunchGroup().getExecutor();
              executorsById.put(executor.getExecutorId().getValue(), executor);

              Collection<Protos.TaskInfo> taskInfos =
                  operation.getLaunchGroup().getTaskGroup().getTasksList();

              launchedTaskNames.addAll(taskInfos.stream()
                  .map(task -> task.getName())
                  .collect(Collectors.toList()));
              launchedTaskInfos.addAll(taskInfos);
              break;
            }
            case RESERVE:
              reservedResources.addAll(operation.getReserve().getResourcesList());
              break;
            default:
              break;
          }
        }
        // Record the accept operation if anything happened:
        if (!executorsById.isEmpty() || !launchedTaskInfos.isEmpty() || !reservedResources.isEmpty()) {
          state.addAcceptCall(
              new AcceptEntry(executorsById.values(), launchedTaskInfos, reservedResources));
        }
      }

      // Finally, verify that exactly the expected tasks were launched across these acceptOffers() calls:
      Assert.assertTrue(
          String.format("Expected launched tasks: %s, got tasks: %s", taskNames, launchedTaskNames),
          launchedTaskNames.containsAll(taskNames) && taskNames.containsAll(launchedTaskNames));
    }

    @Override
    public String getDescription() {
      return String.format("Tasks were launched into a pod: %s", taskNames);
    }
  };
}
 
Example #14
Source File: WrongSetOfAnnotationsTest.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
@Test(expected=MockitoException.class)
public void shouldNotAllowCaptorAndMock() throws Exception {
    MockitoAnnotations.initMocks(new Object() {
        @Mock @Captor ArgumentCaptor captor;
    });
}
 
Example #15
Source File: MockitoBeforeTestNGMethod.java    From mockito-cookbook with Apache License 2.0 4 votes vote down vote up
private void initializeCaptors(Object instance) {
    List<InstanceField> instanceFields = Fields.allDeclaredFieldsOf(instance).filter(annotatedBy(Captor.class)).instanceFields();
    for (InstanceField instanceField : instanceFields) {
        instanceField.set(new CaptorAnnotationProcessor().process(instanceField.annotation(Captor.class), instanceField.jdkField()));
    }
}
 
Example #16
Source File: Expect.java    From dcos-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that an explicit task reconciliation for the task statuses in the provided persister was invoked.
 */
public static Expect reconciledExplicitly(Persister persisterWithStatuses) {
  // Use a custom comparator for sorting: Protos don't implement Comparable
  final Comparator<Protos.TaskStatus> statusComparator = new Comparator<Protos.TaskStatus>() {
    @Override
    public int compare(TaskStatus o1, TaskStatus o2) {
      return o1.getTaskId().getValue().compareTo(o2.getTaskId().getValue());
    }
  };

  return new Expect() {
    // Use this form instead of using ArgumentCaptor.forClass() to avoid problems with typecasting generics:
    @Captor
    private ArgumentCaptor<Collection<Protos.TaskStatus>> statusCaptor;

    @Override
    public void expect(ClusterState state, SchedulerDriver mockDriver) {
      MockitoAnnotations.initMocks(this);
      Mockito.verify(mockDriver, Mockito.atLeastOnce()).reconcileTasks(statusCaptor.capture());
      Set<Protos.TaskStatus> expected = new TreeSet<>(statusComparator);
      // We only send reconcile calls for tasks that aren't already terminal:
      expected.addAll(new StateStore(persisterWithStatuses).fetchStatuses().stream()
          .filter(s -> !TaskUtils.isTerminal(s))
          .collect(Collectors.toList()));
      // Iterate over all reconcile calls, look for any call that had matching arguments.
      // We do this arg ourselves, since the in-mock comparison never matches.
      for (Collection<Protos.TaskStatus> reconcileArgs : statusCaptor.getAllValues()) {
        Set<Protos.TaskStatus> got = new TreeSet<>(statusComparator);
        got.addAll(reconcileArgs);
        if (expected.equals(got)) {
          return; // Found matching call
        }
      }
      Assert.fail(String.format("Expected a task reconcile with arguments: %s, but actual calls were: %s",
          expected, statusCaptor.getAllValues()));
    }

    @Override
    public String getDescription() {
      return String.format("Explicit task reconcile call for statuses: %s",
          new StateStore(persisterWithStatuses).fetchStatuses().stream()
              .map(status -> String.format("%s=%s", status.getTaskId().getValue(), status.getState()))
              .collect(Collectors.toList()));
    }
  };
}
 
Example #17
Source File: Expect.java    From dcos-commons with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies that the resources for the provided task names have been unreserved.
 */
public static Expect unreservedTasks(Collection<String> taskNames) {
  return new Expect() {
    // Use this form instead of using ArgumentCaptor.forClass() to avoid problems with typecasting generics:
    @Captor
    private ArgumentCaptor<Collection<Protos.OfferID>> offerIdsCaptor;

    @Captor
    private ArgumentCaptor<Collection<Protos.Offer.Operation>> operationsCaptor;

    @Override
    public void expect(ClusterState state, SchedulerDriver mockDriver) {
      MockitoAnnotations.initMocks(this);

      Mockito.verify(mockDriver, Mockito.atLeastOnce())
          .acceptOffers(offerIdsCaptor.capture(), operationsCaptor.capture(), any());

      // Check last accepted offer ID was in last offer cycle:
      Protos.OfferID lastAcceptedOfferId = offerIdsCaptor.getValue().iterator().next();
      Set<String> lastCycleOfferIds = state.getLastOfferCycle().stream()
          .map(o -> o.getId().getValue())
          .collect(Collectors.toSet());
      Assert.assertTrue(String.format(
          "Expected last accepted offer in last offer cycle: %s, but last accepted offer was %s",
          lastCycleOfferIds, lastAcceptedOfferId.getValue()),
          lastCycleOfferIds.contains(lastAcceptedOfferId.getValue()));

      // Check unreserved/destroyed resources in operations:
      Collection<String> expectedResourceIds = new ArrayList<>();
      for (String taskName : taskNames) {
        LaunchedTask task = state.getLastLaunchedTask(taskName);
        expectedResourceIds.addAll(ResourceUtils.getResourceIds(task.getTask().getResourcesList()));
        expectedResourceIds.addAll(ResourceUtils.getResourceIds(task.getExecutor().getResourcesList()));
      }
      Assert.assertFalse(String.format("Expected some resource ids for tasks: %s, got none", taskNames),
          expectedResourceIds.isEmpty());
      Collection<String> unreservedResourceIds = new ArrayList<>();
      for (Protos.Offer.Operation operation : operationsCaptor.getValue()) {
        if (operation.getType().equals(Protos.Offer.Operation.Type.DESTROY)) {
          // Destroy volume(s)
          unreservedResourceIds.addAll(
              ResourceUtils.getResourceIds(operation.getDestroy().getVolumesList()));
        } else if (operation.getType().equals(Protos.Offer.Operation.Type.UNRESERVE)) {
          // Unreserve resource(s)
          unreservedResourceIds.addAll(
              ResourceUtils.getResourceIds(operation.getUnreserve().getResourcesList()));
        }
      }
      Assert.assertTrue(
          String.format("Expected unreserved resource ids: %s, got ids: %s",
              expectedResourceIds, unreservedResourceIds),
          unreservedResourceIds.containsAll(expectedResourceIds)
              && expectedResourceIds.containsAll(unreservedResourceIds));
    }

    @Override
    public String getDescription() {
      return String.format("Resources for tasks have been unreserved: %s", taskNames);
    }
  };
}