org.mockito.Mock Java Examples
The following examples show how to use
org.mockito.Mock.
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: UpdateAnalyzerConfigurationServiceTest.java From coderadar with MIT License | 6 votes |
@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); }
Example #2
Source File: PropagationTaskInfoTest.java From syncope with Apache License 2.0 | 6 votes |
@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()); }
Example #3
Source File: ProvisioningProfileTest.java From syncope with Apache License 2.0 | 6 votes |
@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()); }
Example #4
Source File: TestMockito.java From sarl with Apache License 2.0 | 6 votes |
/** 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; }
Example #5
Source File: VertxJobsServiceTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@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()); }
Example #6
Source File: VertxJobsServiceTest.java From kogito-runtimes with Apache License 2.0 | 6 votes |
@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"); }
Example #7
Source File: MockAnnotationProcessor.java From astor with GNU General Public License v2.0 | 6 votes |
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); }
Example #8
Source File: WorkflowResultTest.java From syncope with Apache License 2.0 | 6 votes |
@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()); }
Example #9
Source File: SpyHelper.java From COLA with GNU Lesser General Public License v2.1 | 6 votes |
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; }
Example #10
Source File: ChangePasswordServiceTest.java From coderadar with MIT License | 6 votes |
@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); }
Example #11
Source File: MockitoAfterTestNGMethod.java From mockito-cookbook with Apache License 2.0 | 6 votes |
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; }
Example #12
Source File: UserServiceUnitTest.java From tutorials with MIT License | 6 votes |
@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); }
Example #13
Source File: InjectMocksScanner.java From astor with GNU General Public License v2.0 | 5 votes |
/** * Scan fields annotated by @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 #14
Source File: DB2SqlGenerationVisitorTest.java From virtual-schemas with MIT License | 5 votes |
@BeforeEach void beforeEach(@Mock final ConnectionFactory connectionFactoryMock) { final SqlDialectFactory dialectFactory = new DB2SqlDialectFactory(); final SqlDialect dialect = dialectFactory.createSqlDialect(connectionFactoryMock, AdapterProperties.emptyProperties()); final SqlGenerationContext context = new SqlGenerationContext("test_catalog", "test_schema", false); this.visitor = new DB2SqlGenerationVisitor(dialect, context); }
Example #15
Source File: ResourceGeneratorFactoryTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@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); }
Example #16
Source File: OracleQueryRewriterTest.java From virtual-schemas with MIT License | 5 votes |
@Test void testRewriteWithJdbcConnection(@Mock final ConnectionFactory connectionFactoryMock) throws AdapterException, SQLException { final Connection connectionMock = mockConnection(); Mockito.when(connectionFactoryMock.getConnection()).thenReturn(connectionMock); final AdapterProperties properties = new AdapterProperties(Map.of("CONNECTION_NAME", CONNECTION_NAME)); final SqlDialectFactory dialectFactory = new OracleSqlDialectFactory(); final SqlDialect dialect = dialectFactory.createSqlDialect(connectionFactoryMock, properties); final RemoteMetadataReader metadataReader = new OracleMetadataReader(connectionMock, AdapterProperties.emptyProperties()); final QueryRewriter queryRewriter = new OracleQueryRewriter(dialect, metadataReader, connectionFactoryMock); assertThat(queryRewriter.rewrite(this.statement, EXA_METADATA, properties), equalTo("IMPORT INTO (c1 DECIMAL(18, 0)) FROM JDBC AT " + CONNECTION_NAME + " STATEMENT 'SELECT TO_CHAR(1) FROM \"DUAL\"'")); }
Example #17
Source File: MockitoExtension.java From intellij-spring-assistant with MIT License | 5 votes |
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; }
Example #18
Source File: OracleQueryRewriterTest.java From virtual-schemas with MIT License | 5 votes |
@Test void testRewriteToImportFromOraWithConnectionDetailsInProperties( @Mock final ConnectionFactory connectionFactoryMock) throws AdapterException, SQLException { final AdapterProperties properties = new AdapterProperties(Map.of( // ORACLE_IMPORT_PROPERTY, "true", // ORACLE_CONNECTION_NAME_PROPERTY, "ora_connection")); final SqlDialectFactory dialectFactory = new OracleSqlDialectFactory(); final SqlDialect dialect = dialectFactory.createSqlDialect(connectionFactoryMock, properties); final QueryRewriter queryRewriter = new OracleQueryRewriter(dialect, null, null); assertThat(queryRewriter.rewrite(this.statement, EXA_METADATA, properties), equalTo("IMPORT FROM ORA AT ora_connection STATEMENT 'SELECT TO_CHAR(1) FROM \"DUAL\"'")); }
Example #19
Source File: OracleSqlGenerationVisitorTest.java From virtual-schemas with MIT License | 5 votes |
@BeforeEach void beforeEach(@Mock final ConnectionFactory connectionFactoryMock) throws SQLException { final SqlDialect dialect = new OracleSqlDialectFactory().createSqlDialect(null, AdapterProperties.emptyProperties()); final SqlGenerationContext context = new SqlGenerationContext("test_catalog", "test_schema", false); this.visitor = new OracleSqlGenerationVisitor(dialect, context); }
Example #20
Source File: GenericSqlDialectTest.java From virtual-schemas with MIT License | 5 votes |
@BeforeEach void beforeEach(@Mock final DatabaseMetaData metadataMock, @Mock final Connection connectionMock) throws SQLException { when(metadataMock.supportsMixedCaseIdentifiers()).thenReturn(true); when(metadataMock.supportsMixedCaseQuotedIdentifiers()).thenReturn(true); when(connectionMock.getMetaData()).thenReturn(metadataMock); when(this.connectionFactoryMock.getConnection()).thenReturn(connectionMock); }
Example #21
Source File: MySqlSqlGenerationVisitorTest.java From virtual-schemas with MIT License | 5 votes |
@BeforeEach void beforeEach(@Mock final ConnectionFactory connectionFactoryMock) { final SqlDialectFactory dialectFactory = new MySqlSqlDialectFactory(); final SqlDialect dialect = dialectFactory.createSqlDialect(connectionFactoryMock, AdapterProperties.emptyProperties()); final SqlGenerationContext context = new SqlGenerationContext("test_catalog", "test_schema", false); this.visitor = new MySqlSqlGenerationVisitor(dialect, context); }
Example #22
Source File: ResourceGeneratorFactoryTest.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@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); }
Example #23
Source File: MockitoExtension.java From Mastering-Software-Testing-with-JUnit-5 with MIT License | 5 votes |
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; }
Example #24
Source File: AttributeSerializerTest.java From syncope with Apache License 2.0 | 5 votes |
@Test public void serialize(@Mock Attribute source, @Mock JsonGenerator jgen, @Mock SerializerProvider sp) throws IOException { AttributeSerializer serializer = new AttributeSerializer(); when(source.getValue()).thenReturn(null); serializer.serialize(source, jgen, sp); verify(jgen).writeStartObject(); verify(jgen).writeFieldName("value"); verify(jgen).writeNull(); when(source.getValue()).thenAnswer(ic -> List.of(new GuardedString())); serializer.serialize(source, jgen, sp); verify(jgen).writeObject(any(GuardedString.class)); when(source.getValue()).thenAnswer(ic -> List.of(9000)); serializer.serialize(source, jgen, sp); verify(jgen).writeNumber(anyInt()); when(source.getValue()).thenAnswer(ic -> List.of(9000L)); serializer.serialize(source, jgen, sp); verify(jgen).writeNumber(anyLong()); when(source.getValue()).thenAnswer(ic -> List.of(9000.1)); serializer.serialize(source, jgen, sp); verify(jgen).writeNumber(anyDouble()); when(source.getValue()).thenAnswer(ic -> List.of(Boolean.TRUE)); serializer.serialize(source, jgen, sp); verify(jgen).writeBoolean(anyBoolean()); when(source.getValue()).thenAnswer(ic -> List.of(new byte[] { 9, 0, 0, 0 })); serializer.serialize(source, jgen, sp); verify(jgen).writeString(anyString()); when(source.getValue()).thenAnswer(ic -> List.of("test")); serializer.serialize(source, jgen, sp); verify(jgen).writeString(eq("test")); }
Example #25
Source File: MockitoExtension.java From Mastering-Software-Testing-with-JUnit-5 with MIT License | 5 votes |
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; }
Example #26
Source File: DefaultAnnotationEngine.java From astor with GNU General Public License v2.0 | 5 votes |
@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 #27
Source File: ConnPoolConfUtilsTest.java From syncope with Apache License 2.0 | 5 votes |
@Test public void updateObjectPoolConfiguration(@Mock ObjectPoolConfiguration opc) { ConnPoolConfUtils.updateObjectPoolConfiguration(opc, cpc); verify(opc).setMaxIdle(anyInt()); verify(opc).setMaxObjects(anyInt()); verify(opc).setMaxWait(anyLong()); verify(opc).setMinEvictableIdleTimeMillis(anyLong()); verify(opc).setMinIdle(anyInt()); }
Example #28
Source File: MockParameterFactory.java From junit5-extensions with MIT License | 5 votes |
@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); }
Example #29
Source File: JexlUtilsTest.java From syncope with Apache License 2.0 | 5 votes |
@Test public void addFieldsToContext( @Mock Any<?> any, @Mock AnyTO anyTO, @Mock Realm realm, @Mock RealmTO realmTO) { JexlUtils.addFieldsToContext(new Exception(), context); verify(context, times(2)).set(eq("cause"), any()); String testFullPath = "testFullPath"; when(any.getRealm()).thenReturn(realm); when(realm.getFullPath()).thenReturn(testFullPath); JexlUtils.addFieldsToContext(any, context); verify(context).set("realm", testFullPath); String testRealm = "testRealm"; when(anyTO.getRealm()).thenReturn(testRealm); JexlUtils.addFieldsToContext(anyTO, context); verify(context, times(3)).set("realm", testRealm); String fullPath = "test/full/path"; when(realm.getFullPath()).thenReturn(fullPath); JexlUtils.addFieldsToContext(realm, context); verify(context, times(2)).set("fullPath", fullPath); fullPath = "test/full/path2"; when(realmTO.getFullPath()).thenReturn(fullPath); JexlUtils.addFieldsToContext(realmTO, context); verify(context, times(2)).set("fullPath", fullPath); }
Example #30
Source File: BigQueryQueryRewriterTest.java From virtual-schemas with MIT License | 5 votes |
@BeforeEach void beforeEach(@Mock final ConnectionFactory connectionFactoryMock) throws SQLException { final Connection connectionMock = this.mockConnection(); this.statement = Mockito.mock(SqlStatement.class); when(connectionFactoryMock.getConnection()).thenReturn(connectionMock); final SqlDialectFactory factory = new BigQuerySqlDialectFactory(); final SqlDialect dialect = factory.createSqlDialect(connectionFactoryMock, AdapterProperties.emptyProperties()); final BaseRemoteMetadataReader metadataReader = new BaseRemoteMetadataReader(connectionMock, AdapterProperties.emptyProperties()); this.queryRewriter = new BigQueryQueryRewriter(dialect, metadataReader, connectionFactoryMock); when(connectionMock.createStatement()).thenReturn(this.mockStatement); when(this.mockResultSet.getMetaData()).thenReturn(this.mockResultSetMetaData); when(this.mockStatement.executeQuery(any())).thenReturn(this.mockResultSet); }