类org.mockito.Mock源码实例Demo

下面列出了怎么用org.mockito.Mock的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: sarl   文件: TestMockito.java
/** Replies the type of features in this test that could be or are mocked.
 * A mockable feature is a field that has one of the following annotations:
 * {@link Mock}, {@link InjectMocks}. If the feature is annotation with
 * {@link ManualMocking}, is it not considered by this function.
 *
 * @param typeToExplore is the type to explore.
 * @return the type of mockable features. If it is {@code 0}, no mockable feature was found.
 */
public static int getAutomaticMockableFeatures(Class<?> typeToExplore) {
	int features = 0;
	Class<?> type = typeToExplore;
	while (type != null && !AbstractSarlTest.class.equals(type)) {
		if (type.getAnnotation(ManualMocking.class) != null) {
			return 0;
		}
		for (Field field : type.getDeclaredFields()) {
			if (field.getAnnotation(Mock.class) != null) {
				features |= 0x1;
			} else if (field.getAnnotation(InjectMocks.class) != null) {
				features |= 0x2;
			}
		}
		type = type.getSuperclass();
	}
	return features;
}
 
源代码2 项目: syncope   文件: ProvisioningProfileTest.java
@Test
public void test(
        @Mock Connector connector,
        @Mock PushTask pushTask) {
    boolean dryRun = false;
    ConflictResolutionAction conflictResolutionAction = ConflictResolutionAction.FIRSTMATCH;
    ProvisioningProfile<PushTask, PushActions> profile;
    profile = new ProvisioningProfile<>(connector, pushTask);

    assertEquals(connector, profile.getConnector());
    assertEquals(pushTask, profile.getTask());
    assertEquals(new ArrayList<>(), profile.getResults());
    assertEquals(new ArrayList<>(), profile.getActions());

    profile.setDryRun(dryRun);
    assertFalse(profile.isDryRun());

    profile.setConflictResolutionAction(conflictResolutionAction);
    assertEquals(conflictResolutionAction, profile.getConflictResolutionAction());
}
 
源代码3 项目: syncope   文件: PropagationTaskInfoTest.java
@Test
public void test(@Mock Optional<ConnectorObject> beforeObj) {
    PropagationTaskInfo propagationTaskInfo2 = new PropagationTaskInfo(externalResource);
    Object nullObj = null;

    assertTrue(propagationTaskInfo2.equals(propagationTaskInfo2));
    assertTrue(propagationTaskInfo2.equals(propagationTaskInfo));
    assertFalse(propagationTaskInfo.equals(nullObj));
    assertFalse(propagationTaskInfo.equals(String.class));
    assertEquals(propagationTaskInfo.hashCode(), propagationTaskInfo2.hashCode());
    assertEquals(connector, propagationTaskInfo.getConnector());

    propagationTaskInfo2.setConnector(connector);
    assertEquals(connector, propagationTaskInfo2.getConnector());
    assertEquals(externalResource.getClass(), propagationTaskInfo.getExternalResource().getClass());

    IllegalArgumentException exception =
            assertThrows(IllegalArgumentException.class, () -> propagationTaskInfo.setResource("testResource"));
    assertEquals(exception.getClass(), IllegalArgumentException.class);
    assertNull(propagationTaskInfo2.getResource());
    
    propagationTaskInfo.setBeforeObj(beforeObj);
    assertEquals(beforeObj, propagationTaskInfo.getBeforeObj());
}
 
源代码4 项目: kogito-runtimes   文件: VertxJobsServiceTest.java
@Test
void testScheduleProcessInstanceJob(@Mock HttpRequest<Buffer> request) {
    when(webClient.post(anyString())).thenReturn(request);

    ProcessInstanceJobDescription processInstanceJobDescription = ProcessInstanceJobDescription.of(123,
                                                                                                   ExactExpirationTime.now(),
                                                                                                   "processInstanceId",
                                                                                                   "processId");
    tested.scheduleProcessInstanceJob(processInstanceJobDescription);
    verify(webClient).post("/jobs");
    ArgumentCaptor<Job> jobArgumentCaptor = forClass(Job.class);
    verify(request).sendJson(jobArgumentCaptor.capture(), any(Handler.class));
    Job job = jobArgumentCaptor.getValue();
    assertThat(job.getId()).isEqualTo(processInstanceJobDescription.id());
    assertThat(job.getExpirationTime()).isEqualTo(processInstanceJobDescription.expirationTime().get());
    assertThat(job.getProcessInstanceId()).isEqualTo(processInstanceJobDescription.processInstanceId());
    assertThat(job.getProcessId()).isEqualTo(processInstanceJobDescription.processId());
}
 
源代码5 项目: kogito-runtimes   文件: VertxJobsServiceTest.java
@Test
void testGetScheduleTimeJobNotFound(@Mock HttpRequest<Buffer> request, @Mock HttpResponse<Buffer> response) {
    when(webClient.get(anyString())).thenReturn(request);
    AsyncResult<HttpResponse<Buffer>> asyncResult = mock(AsyncResult.class);
    when(asyncResult.succeeded()).thenReturn(true);
    when(asyncResult.result()).thenReturn(response);
    when(response.statusCode()).thenReturn(404);
    
    doAnswer(invocationOnMock -> {
        Handler<AsyncResult<HttpResponse<Buffer>>> handler = invocationOnMock.getArgument(0);
        executor.submit(() -> handler.handle(asyncResult));
        return null;
    }).when(request).send(any());
    
    assertThatThrownBy(() -> tested.getScheduledTime("123"))
        .hasCauseExactlyInstanceOf(JobNotFoundException.class);
    
    verify(webClient).get("/jobs/123");
}
 
源代码6 项目: astor   文件: MockAnnotationProcessor.java
public Object process(Mock annotation, Field field) {
    MockSettings mockSettings = Mockito.withSettings();
    if (annotation.extraInterfaces().length > 0) { // never null
        mockSettings.extraInterfaces(annotation.extraInterfaces());
    }
    if ("".equals(annotation.name())) {
        mockSettings.name(field.getName());
    } else {
        mockSettings.name(annotation.name());
    }
    if(annotation.serializable()){
    	mockSettings.serializable();
    }

    // see @Mock answer default value
    mockSettings.defaultAnswer(annotation.answer().get());
    return Mockito.mock(field.getType(), mockSettings);
}
 
源代码7 项目: syncope   文件: WorkflowResultTest.java
@Test
public void test(@Mock PropagationByResource<String> propByRes) {
    String result = "result";
    Set<String> performedTasks = new HashSet<>();
    performedTasks.add("TEST");
    WorkflowResult<String> workflowResult = new WorkflowResult<>(result, propByRes, performedTasks);
    WorkflowResult<String> workflowResult2 = new WorkflowResult<>(result, propByRes, performedTasks);
    
    assertTrue(workflowResult.equals(workflowResult));
    assertTrue(workflowResult.equals(workflowResult2));
    assertFalse(workflowResult.equals(null));
    assertFalse(workflowResult.equals(String.class));
    
    result = "newResult";
    workflowResult.setResult(result);
    assertEquals(result, workflowResult.getResult());
    
    assertEquals(propByRes, workflowResult2.getPropByRes());
}
 
源代码8 项目: COLA   文件: SpyHelper.java
private Set<Object> getOriTargetSet(){
    Set<Object> oriTargetSet = new HashSet<>();
    Set<Field> mockFields = new HashSet<Field>();
    new InjectAnnotationScanner(ownerClazz, Spy.class).addTo(mockFields);
    new InjectAnnotationScanner(ownerClazz, Mock.class).addTo(mockFields);
    if(mockFields.size() == 0){
        return new HashSet<>();
    }
    if(!isSpringContainer()){
        return new HashSet<>();
    }
    for(Field field : mockFields){
        Object oriTarget = getBean(field);
        if(oriTarget == null){
            continue;
        }
        oriTargetSet.add(oriTarget);
    }
    return oriTargetSet;
}
 
源代码9 项目: coderadar   文件: ChangePasswordServiceTest.java
@Test
void changePasswordSuccessfully(@Mock User userToUpdateMock) {
  // given
  String refreshToken = "refresh-token";
  String newPassword = "new-password";

  ChangePasswordCommand command = new ChangePasswordCommand(refreshToken, newPassword);

  when(refreshTokenServiceMock.getUser(refreshToken)).thenReturn(userToUpdateMock);

  // when
  testSubject.changePassword(command);

  // then
  verify(userToUpdateMock).setPassword(anyString());
  verify(changePasswordPortMock).changePassword(userToUpdateMock);
  verify(refreshTokenPortMock).deleteByUser(userToUpdateMock);
}
 
private Set<Object> instanceMocksIn(Object instance, Class<?> clazz) {
    Set<Object> instanceMocks = new HashSet<Object>();
    Field[] declaredFields = clazz.getDeclaredFields();
    for (Field declaredField : declaredFields) {
        if (declaredField.isAnnotationPresent(Mock.class) || declaredField.isAnnotationPresent(Spy.class)) {
            declaredField.setAccessible(true);
            try {
                Object fieldValue = declaredField.get(instance);
                if (fieldValue != null) {
                    instanceMocks.add(fieldValue);
                }
            } catch (IllegalAccessException e) {
                throw new MockitoException("Could not access field " + declaredField.getName());
            }
        }
    }
    return instanceMocks;
}
 
源代码11 项目: tutorials   文件: UserServiceUnitTest.java
@Test
void givenValidUser_whenSaveUser_thenSucceed(@Mock MailClient mailClient) {
    // Given
    user = new User("Jerry", 12);
    when(userRepository.insert(any(User.class))).then(new Answer<User>() {
        int sequence = 1;
        
        @Override
        public User answer(InvocationOnMock invocation) throws Throwable {
            User user = (User) invocation.getArgument(0);
            user.setId(sequence++);
            return user;
        }
    });

    userService = new DefaultUserService(userRepository, settingRepository, mailClient);

    // When
    User insertedUser = userService.register(user);
    
    // Then
    verify(userRepository).insert(user);
    Assertions.assertNotNull(user.getId());
    verify(mailClient).sendUserRegistrationMail(insertedUser);
}
 
@Test
void updateAnalyzerConfigurationUpdatesNameAndEnabled(
    @Mock AnalyzerConfiguration existingConfigurationMock) {
  // given
  long configurationId = 1L;
  String newConfigurationName = "new analyzer name";

  UpdateAnalyzerConfigurationCommand command =
      new UpdateAnalyzerConfigurationCommand(newConfigurationName, false);

  when(getConfigurationPortMock.getAnalyzerConfiguration(configurationId))
      .thenReturn(existingConfigurationMock);

  when(listAnalyzerServiceMock.listAvailableAnalyzers())
      .thenReturn(Collections.singletonList("new analyzer name"));

  // when
  testSubject.update(command, 1L, 2L);

  // then
  verify(existingConfigurationMock, never()).setId(anyLong());
  verify(existingConfigurationMock).setAnalyzerName(newConfigurationName);
  verify(existingConfigurationMock).setEnabled(false);

  verify(updateConfigurationPortMock).update(existingConfigurationMock);
}
 
源代码13 项目: sdn-rx   文件: SingleValueMappingFunctionTest.java
SingleValueMappingFunctionTest(@Mock TypeSystem typeSystem, @Mock Record record) {
	this.typeSystem = typeSystem;
	this.record = record;
	this.conversionService = new DefaultConversionService();
	new Neo4jConversions().registerConvertersIn((ConverterRegistry) this.conversionService);

}
 
@Test
void testCreateQuarkus(@Mock GeneratorContext generatorContext) {
    when(generatorContext.getBuildContext()).thenReturn(new QuarkusKogitoBuildContext(p -> true));
    Optional<AbstractResourceGenerator> context = tested.create(generatorContext,
                                                                process,
                                                                MODEL_FQCN,
                                                                PROCESS_FQCN,
                                                                APP_CANONICAL_NAME);
    assertThat(context.isPresent()).isTrue();
    assertThat(context.get()).isExactlyInstanceOf(ResourceGenerator.class);
}
 
@Test
void testCreateQuarkusReactive(@Mock GeneratorContext generatorContext) {
    when(generatorContext.getApplicationProperty(GeneratorConfig.KOGITO_REST_RESOURCE_TYPE_PROP)).thenReturn(Optional.of("reactive"));
    when(generatorContext.getBuildContext()).thenReturn(new QuarkusKogitoBuildContext(p -> true));

    Optional<AbstractResourceGenerator> context = tested.create(generatorContext,
                                                                process,
                                                                MODEL_FQCN,
                                                                PROCESS_FQCN,
                                                                APP_CANONICAL_NAME);
    assertThat(context.isPresent()).isTrue();
    assertThat(context.get()).isExactlyInstanceOf(ReactiveResourceGenerator.class);
}
 
源代码16 项目: AuthMeReloaded   文件: CheckTestMocks.java
private static boolean isTestClassWithMocks(Class<?> clazz) {
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(Mock.class)) {
            return true;
        }
    }
    return false;
}
 
@Test
void testDoGetWorkItemsInProcessInstance(@Mock WorkItem workItem) {
    when(processInstance.workItems(any(SecurityPolicy.class))).thenReturn(Collections.singletonList(workItem));
    Object response = tested.doGetWorkItemsInProcessInstance(PROCESS_ID, PROCESS_INSTANCE_ID);
    assertThat(response).isInstanceOf(List.class);
    assertThat(((List)response).get(0)).isEqualTo(workItem);
}
 
@SuppressWarnings({"deprecation", "unchecked"})
private Collection<Object> instanceMocksOf(Object instance) {
    return Fields.allDeclaredFieldsOf(instance)
                                        .filter(annotatedBy(Mock.class,
                                                            Spy.class,
                                                            MockitoAnnotations.Mock.class))
                                        .notNull()
                                        .assignedValues();
}
 
源代码19 项目: syncope   文件: JexlUtilsTest.java
@Test
public void addDerAttrsToContext(
        @Mock DerAttrHandler derAttrHandler,
        @Mock Any<?> any,
        @Mock DerSchema derSchema) {
    Map<DerSchema, String> derAttrs = new HashMap<>();
    derAttrs.put(derSchema, expression);

    when(derAttrHandler.getValues(any())).thenReturn(derAttrs);
    JexlUtils.addDerAttrsToContext(any, derAttrHandler, context);
    verify(context).set(derAttrs.get(derSchema), expression);
}
 
源代码20 项目: syncope   文件: LDAPPasswordPullActionsTest.java
@Test
public void after(@Mock User user) throws JobExecutionException {
    when(userDAO.find(entity.getKey())).thenReturn(user);

    ldapPasswordPullActions.after(profile, syncDelta, entity, result);

    verify(user).setEncodedPassword(anyString(), any(CipherAlgorithm.class));
    assertNull(ReflectionTestUtils.getField(ldapPasswordPullActions, "encodedPassword"));
    assertNull(ReflectionTestUtils.getField(ldapPasswordPullActions, "cipher"));
}
 
源代码21 项目: java-spring-rabbitmq   文件: TestUtils.java
private static Object[] getObjectsAnnotatedWithMock(final Object testClass) {
  return Arrays.stream(testClass.getClass().getDeclaredFields())
      .filter(input -> input.isAnnotationPresent(Mock.class))
      .map(
          input -> {
            ReflectionUtils.makeAccessible(input);
            return ReflectionUtils.getField(input, testClass);
          })
      .toArray();
}
 
源代码22 项目: AuthMeReloaded   文件: CheckTestMocks.java
private static Set<Class<?>> getMocks(Class<?> clazz) {
    Set<Class<?>> result = new HashSet<>();
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(Mock.class)) {
            result.add(field.getType());
        }
    }
    return result;
}
 
源代码23 项目: syncope   文件: DBPasswordPullActionsTest.java
@Test
public void after(@Mock User user) throws JobExecutionException {
    when(userDAO.find(user.getKey())).thenReturn(user);

    dBPasswordPullActions.after(profile, syncDelta, userTO, result);

    verify(user).setEncodedPassword(anyString(), any(CipherAlgorithm.class));
    assertNull(ReflectionTestUtils.getField(dBPasswordPullActions, "encodedPassword"));
    assertNull(ReflectionTestUtils.getField(dBPasswordPullActions, "cipher"));
}
 
源代码24 项目: syncope   文件: JobNamerTest.java
@Test
public void getJobKey(@Mock Task task) {
    String uuid = UUID.randomUUID().toString();
    when(task.getKey()).thenReturn(uuid);
    assertTrue(EqualsBuilder.reflectionEquals(new JobKey("taskJob" + task.getKey(), Scheduler.DEFAULT_GROUP),
            JobNamer.getJobKey(task)));
}
 
private MockUp<?> mockProfileListenerEnvVar() {
	Map<String, String> env = System.getenv();
	return new MockUp<System>() {
		@mockit.Mock
		public String getenv(String name) {
			if (name.equalsIgnoreCase(ProfileApplicationListener.IGNORE_PROFILEAPPLICATIONLISTENER_ENVVAR_NAME)) {
				return "true";
			}
			return env.get(name);
		}
	};
}
 
源代码26 项目: syncope   文件: GuardedStringSerializerTest.java
@Test
public void serialize(
        @Mock JsonGenerator jgen, 
        @Mock SerializerProvider sp) throws IOException {
    serializer.serialize(new GuardedString(), jgen, sp);
    verify(jgen).writeBooleanField(READONLY, false);
    verify(jgen).writeBooleanField(DISPOSED, false);
    verify(jgen).writeStringField(eq(ENCRYPTED_BYTES), anyString());
    verify(jgen).writeStringField(eq(BASE64_SHA1_HASH), anyString());
    verify(jgen).writeEndObject();
}
 
private String getMockName(Parameter parameter) {
  String explicitMockName = parameter.getAnnotation(Mock.class).name().trim();
  if (!explicitMockName.isEmpty()) {
    return explicitMockName;
  } else if (parameter.isNamePresent()) {
    return parameter.getName();
  }
  return null;
}
 
源代码28 项目: junit5-extensions   文件: MockParameterFactory.java
@Override
public Object getParameterValue(Parameter parameter) {
  Mock annotation = parameter.getAnnotation(Mock.class);
  MockSettings settings = Mockito.withSettings();
  if (annotation.extraInterfaces().length > 0) {
    settings.extraInterfaces(annotation.extraInterfaces());
  }
  if (annotation.serializable()) {
    settings.serializable();
  }
  settings.name(annotation.name().isEmpty() ? parameter.getName() : annotation.name());
  settings.defaultAnswer(annotation.answer());

  return Mockito.mock(parameter.getType(), settings);
}
 
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name()
            .trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    } else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
 
private String getMockName(Parameter parameter) {
    String explicitMockName = parameter.getAnnotation(Mock.class).name()
            .trim();
    if (!explicitMockName.isEmpty()) {
        return explicitMockName;
    } else if (parameter.isNamePresent()) {
        return parameter.getName();
    }
    return null;
}
 
 类所在包
 类方法
 同包方法