/** * Verify that a stateful but not state aware source is wrapped into a TimewarpEventSourceAdapter * before it is added to the process. */ @Test public void testAddStatefulSource() { // We cannot mock here because we'd loose annotations @Stateful final class Source implements EventSource { @Override public Event peek(long currentSimtime) { return null; } @Override public void remove(Event event) {} } Source source = new Source(); builder.add(source); ArgumentCaptor<EventSource> argument = ArgumentCaptor.forClass(EventSource.class); verify(process).addEventSource(argument.capture()); EventSource addedSource = argument.getValue(); assertNotNull(addedSource); assertTrue(addedSource instanceof TimewarpEventSourceAdapter); verifyNoMoreInteractions(process); verify(service).register(source); verify(service).register(addedSource); verifyNoMoreInteractions(service); }
@Test public void testAddStatefulEventGenerator() { @Stateful final class Generator implements StatefulEventGenerator { @Override public Event poll() { return null; } } Generator generator = new Generator(); builder.add(generator); ArgumentCaptor<EventSource> argument = ArgumentCaptor.forClass(EventSource.class); verify(process).addEventSource(argument.capture()); EventSource addedSource = argument.getValue(); assertNotNull(addedSource); assertTrue(addedSource instanceof TimewarpEventSourceAdapter); verifyNoMoreInteractions(process); // We know the generator and the source but don't have the adapter. // So we simply check that the generator and the source got registered // and require 3 calls overall. verify(service).register(generator); verify(service).register(addedSource); verify(service, times(3)).register(any()); verifyNoMoreInteractions(service); }
@Test public void testAddProcess() { final class Process implements DiscreteEventProcess { @Override public void dispatchEvent(Event e) {} @Override public void offer(Event event) {} @Override public Event peek(long currentSimtime) { return null; } @Override public void remove(Event event) {} } Process dummy = new Process(); builder.add(dummy); verify(process).addEventSource(dummy); verify(process).addEventSink(dummy); verify(process).addEventDispatcher(dummy); verifyNoMoreInteractions(process); verify(service).register(dummy); verifyNoMoreInteractions(service); }
@Test public void testInstrumentationLegacyClassOtherType() throws Exception { ClassVisitor classVisitor = TypeConstantAdjustment.INSTANCE.wrap( mock(TypeDescription.class), this.classVisitor, mock(Implementation.Context.class), mock(TypePool.class), new FieldList.Empty<FieldDescription.InDefinedShape>(), new MethodList.Empty<MethodDescription>(), IGNORED, IGNORED); classVisitor.visit( ClassFileVersion.JAVA_V4.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[] {BAZ}); MethodVisitor methodVisitor = classVisitor.visitMethod(FOOBAR, FOO, BAR, QUX, new String[] {BAZ}); assertThat(methodVisitor, not(this.methodVisitor)); methodVisitor.visitLdcInsn(FOO); verify(this.classVisitor) .visit( ClassFileVersion.JAVA_V4.getMinorMajorVersion(), FOOBAR, FOO, BAR, QUX, new String[] {BAZ}); verify(this.classVisitor).visitMethod(FOOBAR, FOO, BAR, QUX, new String[] {BAZ}); verifyNoMoreInteractions(this.classVisitor); verify(this.methodVisitor).visitLdcInsn(FOO); verifyNoMoreInteractions(this.methodVisitor); }
public void testParams() { Map<String, Object> params = Maps.newHashMap(); ActionDef def = Mockito.mock(ActionDef.class); Action test = new MyAction(null, def, params); LoggingContext.KeyValueLogger logger = Mockito.mock(LoggingContext.KeyValueLogger.class); assertSame("params should be initialized", params, test.getParams()); params.put("a", "b"); test.logParams(logger); // logable values of null should avoid calls to the logger. Mockito.verifyNoMoreInteractions(logger); Mockito.when(def.getLoggableParams()).thenReturn(Lists.newArrayList("a", "b")); test.logParams(logger); Mockito.verify(logger, Mockito.times(1)).log("a", "b"); Mockito.verify(logger, Mockito.times(1)).log("b", "null"); Mockito.verifyNoMoreInteractions(logger); test = new MyAction(null, def, null); assertEquals("params can be initialized to null", null, test.getParams()); test.logParams(logger); // params of null should avoid calls to the logger. Mockito.verifyNoMoreInteractions(logger); }
@Test public void shouldSetTimerToFlushFilesToDisk_EveryHour() { final TimerTask[] tasks = new TimerTask[1]; final EntryRepoFactory repoFactory = mock(EntryRepoFactory.class); final Timer timer = new Timer() { @Override public void schedule(TimerTask task, long delay, long period) { if (task instanceof TlbServerInitializer.SyncToDisk) { tasks[0] = task; assertThat(delay, is(0l)); assertThat(period, is((long) TlbServerInitializer.MILLS_PER_HOUR)); } } }; new TlbServerInitializer(new SystemEnvironment(systemEnv), timer) { @Override EntryRepoFactory repoFactory() { return repoFactory; } }.init(); verify(repoFactory).registerExitHook(); verifyNoMoreInteractions(repoFactory); tasks[0].run(); verify(repoFactory).syncReposToDisk(); verifyNoMoreInteractions(repoFactory); }
@Test public void closeAfterClientHalfCloseShouldSucceed() throws Exception { // Client half-closes. Listener gets halfClosed() stream().inboundDataReceived(new EmptyByteBuf(UnpooledByteBufAllocator.DEFAULT), true); assertTrue(stream().canSend()); verify(serverListener).halfClosed(); // Server closes. Status sent stream().close(Status.OK, trailers); assertTrue(stream().isClosed()); verifyNoMoreInteractions(serverListener); verify(writeQueue) .enqueue( new SendResponseHeadersCommand( STREAM_ID, new DefaultHttp2Headers() .status(new AsciiString("200")) .set(new AsciiString("content-type"), new AsciiString("application/grpc")) .set(new AsciiString("grpc-status"), new AsciiString("0")), true), true); // Sending and receiving complete. Listener gets closed() stream().complete(); verify(serverListener).closed(Status.OK); verifyNoMoreInteractions(serverListener); }
@Test public void testBoxing() throws Exception { StackManipulation boxingStackManipulation = PrimitiveBoxingDelegate.forPrimitive(primitiveTypeDescription) .assignBoxedTo(targetType, chainedAssigner, Assigner.Typing.STATIC); assertThat(boxingStackManipulation.isValid(), is(true)); StackManipulation.Size size = boxingStackManipulation.apply(methodVisitor, implementationContext); assertThat(size.getSizeImpact(), is(sizeChange)); assertThat(size.getMaximalSize(), is(0)); verify(primitiveTypeDescription).represents(primitiveType); verify(primitiveTypeDescription, atLeast(1)).represents(any(Class.class)); verifyNoMoreInteractions(primitiveTypeDescription); verify(chainedAssigner) .assign(referenceTypeDescription.asGenericType(), targetType, Assigner.Typing.STATIC); verifyNoMoreInteractions(chainedAssigner); verify(methodVisitor) .visitMethodInsn( Opcodes.INVOKESTATIC, referenceTypeDescription.getInternalName(), VALUE_OF, boxingMethodDescriptor, false); verifyNoMoreInteractions(methodVisitor); verify(stackManipulation, atLeast(1)).isValid(); verify(stackManipulation).apply(methodVisitor, implementationContext); verifyNoMoreInteractions(stackManipulation); }
@Test public void testLegalSlackBinding() throws Exception { when(target.getIndex()).thenReturn(1); when(annotation.value()).thenReturn(AllArguments.Assignment.SLACK); when(stackManipulation.isValid()).thenReturn(false); when(source.getParameters()) .thenReturn(new ParameterList.Explicit.ForTypes(source, firstSourceType, secondSourceType)); when(source.isStatic()).thenReturn(false); when(targetType.isArray()).thenReturn(true); when(targetType.getComponentType()).thenReturn(componentType); when(componentType.getStackSize()).thenReturn(StackSize.SINGLE); when(target.getType()).thenReturn(targetType); when(target.getDeclaredAnnotations()).thenReturn(new AnnotationList.Empty()); when(rawComponentType.getInternalName()).thenReturn(FOO); MethodDelegationBinder.ParameterBinding<?> parameterBinding = AllArguments.Binder.INSTANCE.bind( annotationDescription, source, target, implementationTarget, assigner); MethodVisitor methodVisitor = mock(MethodVisitor.class); Implementation.Context implementationContext = mock(Implementation.Context.class); StackManipulation.Size size = parameterBinding.apply(methodVisitor, implementationContext); assertThat(size.getSizeImpact(), is(1)); assertThat(size.getMaximalSize(), is(1)); verify(methodVisitor).visitInsn(Opcodes.ICONST_0); verify(methodVisitor).visitTypeInsn(Opcodes.ANEWARRAY, FOO); verifyNoMoreInteractions(methodVisitor); verifyZeroInteractions(implementationContext); assertThat(parameterBinding.isValid(), is(true)); verify(source, atLeast(1)).getParameters(); verify(source, atLeast(1)).isStatic(); verify(target, atLeast(1)).getType(); verify(target, atLeast(1)).getDeclaredAnnotations(); verify(assigner).assign(firstSourceType, componentType, Assigner.Typing.STATIC); verify(assigner).assign(secondSourceType, componentType, Assigner.Typing.STATIC); verifyNoMoreInteractions(assigner); }
@Test public void canAddManyListenersPerThread() { LogEventListener listener1 = mock(LogEventListener.class); LogEventListener listener2 = mock(LogEventListener.class); LogEventListener listener3 = mock(LogEventListener.class); SelenideLogger.addListener("simpleReport", listener1); SelenideLogger.addListener("softAsserts", listener2); SelenideLogger.addListener("userProvided", listener3); WebElement webElement = mock(WebElement.class); when(webdriver.findElement(By.cssSelector("div"))).thenReturn(webElement); when(webElement.isDisplayed()).thenReturn(true); $("div").click(); verifyEvent(listener1); verifyEvent(listener2); verifyEvent(listener3); verifyNoMoreInteractions(listener1, listener2, listener3); reset(listener1, listener2, listener3); SelenideLogger.removeListener("simpleReport"); SelenideLogger.removeListener("softAsserts"); $("div").click(); verifyEvent(listener3); verifyNoMoreInteractions(listener1, listener2, listener3); }
@Test public void testPulseMetricsForUploadAttempts() throws Exception { storageSystem.succeedOnAttempt(2); File pendingFile = new File(tempStageDir, "pending.json.snappy"); Files.copy(new File(Resources.getResource("pending.json.snappy").toURI()), pendingFile); // attempt 1 to upload from staging directory fails and file is moved to retry directory uploader = new S3Uploader( storageSystem, serverConfig, new EventPartitioner(), executor, executor, s3UploaderStats); uploader.start(); S3UploaderStats s3UploaderStatsArgumentVerifier = testingReportCollectionFactory.getArgumentVerifier(S3UploaderStats.class); verify(s3UploaderStatsArgumentVerifier).uploadAttempts(ARBITRARY_EVENT_TYPE, FAILURE); verify(s3UploaderStatsArgumentVerifier).processedTime(ARBITRARY_EVENT_TYPE); verifyNoMoreInteractions(s3UploaderStatsArgumentVerifier); S3UploaderStats s3UploaderStatsReportCollection = testingReportCollectionFactory.getReportCollection(S3UploaderStats.class); CounterStat uploadAttemptsCounterStat = s3UploaderStatsReportCollection.uploadAttempts(ARBITRARY_EVENT_TYPE, FAILURE); TimeStat processedTimeTimerStat = s3UploaderStatsReportCollection.processedTime(ARBITRARY_EVENT_TYPE); verify(uploadAttemptsCounterStat).add(1); verify(processedTimeTimerStat).time(); verifyNoMoreInteractions(uploadAttemptsCounterStat); verifyNoMoreInteractions(processedTimeTimerStat); }
@Test public void testAddStatelessEventGenerator() { final class Generator implements StatelessEventGenerator { @Override public Event peek(long simtime) { return null; } } Generator generator = new Generator(); builder.add(generator); ArgumentCaptor<EventSource> argument = ArgumentCaptor.forClass(EventSource.class); verify(process).addEventSource(argument.capture()); EventSource addedSource = argument.getValue(); assertNotNull(addedSource); assertTrue(addedSource instanceof EventSourceStatelessGeneratorAdapter); verifyNoMoreInteractions(process); verify(service).register(generator); verify(service).register(addedSource); verifyNoMoreInteractions(service); }
@Test public void testGroupCollapseFilterFieldAllFiltered() throws IOException { mockResponse(true); when(rb.grouping()).thenReturn(true); when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(true); when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FL)) .thenReturn("price,discount,isCloseout,color,colorFamily"); when(params.get(GroupCollapseParams.GROUP_COLLAPSE_FF)).thenReturn(FIELD_CLOSEOUT); component.process(rb); verify(rb).grouping(); verify(rb).getGroupingSpec(); verify(params).getBool(GroupCollapseParams.GROUP_COLLAPSE, false); verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FL); verify(params).get(GroupCollapseParams.GROUP_COLLAPSE_FF); verify(params).getParams(GroupCollapseParams.GROUP_COLLAPSE_FQ); verifyNoMoreInteractions(rb); verifyNoMoreInteractions(params); ArgumentCaptor<NamedList> namedListArgument = ArgumentCaptor.forClass(NamedList.class); verify(rsp).add(eq("groups_summary"), namedListArgument.capture()); NamedList groupsSummary = namedListArgument.getValue(); NamedList productId = (NamedList) groupsSummary.get("productId"); assertNotNull(productId); Set<String> colorFamilies = new HashSet<String>(); colorFamilies.add("RedColorFamily"); colorFamilies.add("BlackColorFamily"); verifyProductSummary( (NamedList) productId.get("product1"), 80.0f, 100.0f, 0.0f, 20.0f, 2, colorFamilies); colorFamilies = new HashSet<String>(); colorFamilies.add("OrangeColorFamily"); colorFamilies.add("BrownColorFamily"); verifyProductSummary( (NamedList) productId.get("product2"), 60.0f, 80.0f, 20.0f, 40.0f, 2, colorFamilies); }
@Test public void delete_by_photoDeleteForm() { // given List<Long> ids = new ArrayList<Long>(); ids.add(expectedPhotoList.get(0).getId()); ids.add(expectedPhotoList.get(1).getId()); PhotoDeleteForm photoDeleteForm = new PhotoDeleteForm(); photoDeleteForm.setIds(ids); when(photoRepository.findAll(ids)).thenReturn(expectedPhotoList.subList(0, 2)); photoService.setPhotoRepository(photoRepository); photoService.setPhotoImageService(photoImageService); // execute List<Photo> deletedPhotos = photoService.delete(photoDeleteForm); // assert assertEquals(2, deletedPhotos.size()); PhotoTestUtils.assertPhoto(expectedPhotoList.get(0), deletedPhotos.get(0)); PhotoTestUtils.assertPhoto(expectedPhotoList.get(1), deletedPhotos.get(1)); verify(photoRepository, times(1)).findAll(ids); verify(photoRepository, times(1)).delete(deletedPhotos); verify(photoImageService, times(1)).delete(ids.get(0)); verify(photoImageService, times(1)).delete(ids.get(1)); verifyNoMoreInteractions(photoRepository); verifyNoMoreInteractions(photoImageService); }
@Test public void testConstructorAndDispose() throws Exception { verifyNoMoreInteractions(m_resultProcessor); assertNotNull(m_httpRecording.getParameters()); assertSame(m_httpRecording.getParameters(), m_httpRecording.getParameters()); m_httpRecording.dispose(); m_httpRecording.dispose(); verify(m_resultProcessor, times(2)).process(m_recordingCaptor.capture()); final HttpRecordingDocument recording = m_recordingCaptor.getAllValues().get(0); final HttpRecordingDocument recording2 = m_recordingCaptor.getAllValues().get(1); XMLBeansUtilities.validate(recording); XMLBeansUtilities.validate(recording2); assertNotSame("We get a copy", recording, recording2); final Metadata metadata = recording.getHttpRecording().getMetadata(); assertTrue(metadata.getVersion().length() > 0); assertNotNull(metadata.getTime()); assertEquals(0, recording.getHttpRecording().getCommonHeadersArray().length); assertEquals(0, recording.getHttpRecording().getBaseUriArray().length); assertEquals(0, recording.getHttpRecording().getPageArray().length); verifyNoMoreInteractions(m_resultProcessor); final IOException exception = new IOException("Eat me"); doThrow(exception).when(m_resultProcessor).process(isA(HttpRecordingDocument.class)); m_httpRecording.dispose(); verify(m_logger).error(exception.getMessage(), exception); }
public void testSetDuringDependencyNodeOperations() { DoubleObjectStorage storage = mock(DoubleObjectStorage.class); when(storage.load(42d)).thenReturn(Storage.UNDEFINED, '*'); DoubleCharacterCalculatable calculatable = mock(DoubleCharacterCalculatable.class); MxResource r = mock(MxResource.class); when(calculatable.calculate("123", 42d)).thenThrow(new ResourceOccupied(r)); DoubleCharacterCache cache = (DoubleCharacterCache) Wrapping.getFactory( new Signature(double.class, Object.class), new Signature(double.class, char.class), false) .wrap("123", calculatable, storage, new MutableStatisticsImpl()); cache.setDependencyNode(DependencyTracker.DUMMY_NODE); assert cache.getStatistics().getHits() == 0; assert cache.getStatistics().getMisses() == 0; assert cache.getOrCreate(42d) == '*'; assert cache.getStatistics().getHits() == 1; assert cache.getStatistics().getMisses() == 0; verify(storage, atLeast(2)).load(42d); verifyNoMoreInteractions(storage); verify(calculatable).calculate("123", 42d); verifyNoMoreInteractions(calculatable); }
@Test public void shouldDelegateInvocationAndInvokeBeforeAndAfterMethods() throws Exception { // given StatementContext delegate = mock(StatementContext.class); Object[] arguments = arguments(method.getParameterTypes()); Object expectedResult = null; if (method.getReturnType() != void.class) { expectedResult = sample(method.getReturnType()); method.invoke(doReturn(expectedResult).when(delegate), arguments); } MyStatementContext context = new MyStatementContext(delegate); // when Object result = method.invoke(context, arguments); // then method.invoke(verify(delegate), arguments); verifyNoMoreInteractions(delegate); if (method.getReturnType() != void.class) { assertEquals(expectedResult, result); } // Verify before and after methods InOrder order = inOrder(context.checking); order.verify(context.checking).beforeOperation(); if (method.operation != null) { order.verify(context.checking).beforeReadOrWriteOperation(method.operation); order.verify(context.checking).afterReadOrWriteOperation(method.operation); } order.verify(context.checking).afterOperation(); verifyNoMoreInteractions(context.checking); }
@Test public void shouldCantUnbombOnBoard() { shouldBoardWith(new Sapper(1, 1)); assertBoard("☼☼☼☼☼\n" + "☼ ☼\n" + "☼ ☼\n" + "☼☺ ☼\n" + "☼☼☼☼☼\n"); unbombLeft(); verifyNoMoreInteractions(listener); assertBoard("☼☼☼☼☼\n" + "☼ ☼\n" + "☼ ☼\n" + "☼☺ ☼\n" + "☼☼☼☼☼\n"); unbombDown(); verifyNoMoreInteractions(listener); assertBoard("☼☼☼☼☼\n" + "☼ ☼\n" + "☼ ☼\n" + "☼☺ ☼\n" + "☼☼☼☼☼\n"); moveRight(); moveRight(); reset(listener); unbombRight(); verifyNoMoreInteractions(listener); assertBoard("☼☼☼☼☼\n" + "☼ ☼\n" + "☼ ☼\n" + "☼ ☺☼\n" + "☼☼☼☼☼\n"); moveUp(); moveUp(); reset(listener); unbombUp(); verifyNoMoreInteractions(listener); assertBoard("☼☼☼☼☼\n" + "☼ ☺☼\n" + "☼ ☼\n" + "☼ ☼\n" + "☼☼☼☼☼\n"); }
@Test public void testStopRestartable() throws Exception { RxPresenter presenter = new RxPresenter(); presenter.onCreate(null); Func0<Subscription> restartable = mock(Func0.class); Subscription subscription = mock(Subscription.class); when(restartable.call()).thenReturn(subscription); when(subscription.isUnsubscribed()).thenReturn(false); presenter.restartable(1, restartable); verifyNoMoreInteractions(restartable); presenter.start(1); verify(restartable, times(1)).call(); verifyNoMoreInteractions(restartable); presenter.stop(1); Bundle bundle = BundleMock.mock(); presenter.onSave(bundle); presenter = new RxPresenter(); presenter.onCreate(bundle); presenter.restartable(1, restartable); verify(restartable, times(1)).call(); verifyNoMoreInteractions(restartable); }
@Test public void testFailsOnVerifyFile() throws Exception { File invalidJsonFile = new File(tempStageDir, "invalidjson2.snappy"); Files.copy(new File(Resources.getResource("invalidjson2.snappy").toURI()), invalidJsonFile); assertTrue(invalidJsonFile.exists()); uploader = new S3Uploader( storageSystem, serverConfig, new EventPartitioner(), executor, executor, s3UploaderStats); uploader.start(); assertFalse(invalidJsonFile.exists()); assertTrue(new File(tempStageDir.getPath() + "/failed", invalidJsonFile.getName()).exists()); assertFalse(storageSystem.hasReceivedFile(invalidJsonFile)); S3UploaderStats s3UploaderStatsArgumentVerifier = testingReportCollectionFactory.getArgumentVerifier(S3UploaderStats.class); verify(s3UploaderStatsArgumentVerifier).processedFiles(UNKNOWN_EVENT_TYPE, CORRUPT); verifyNoMoreInteractions(s3UploaderStatsArgumentVerifier); CounterStat processedFilesCounterStat = testingReportCollectionFactory .getReportCollection(S3UploaderStats.class) .processedFiles(UNKNOWN_EVENT_TYPE, CORRUPT); verify(processedFilesCounterStat).add(1); verifyNoMoreInteractions(processedFilesCounterStat); }
@Test public void testAddEventSinkWithFilter() { final class Sink implements EventSink { @Override public void offer(Event event) {} } final class Condition implements EventCondition { @Override public boolean match(Event e) { return false; } } Sink sink = new Sink(); Condition condition = new Condition(); builder.add(sink, condition); ArgumentCaptor<EventSink> argument = ArgumentCaptor.forClass(EventSink.class); verify(process).addEventSink(argument.capture()); EventSink addedSink = argument.getValue(); assertNotNull(addedSink); assertTrue(addedSink instanceof FilteredEventSink); verifyNoMoreInteractions(process); verify(service).register(sink); verify(service).register(addedSink); verifyNoMoreInteractions(service); }
/** * Test prefetchDeltaSignerInfo for failing requests where a previous request on a different * domain has already succeeded. The failing request should also appear to succeed. */ public void test_prefetchDeltaSignerInfo5() throws Exception { // This would fail if the next (immediate) request didn't succeed SignerInfoPrefetchResultListener failListener = mock(SignerInfoPrefetchResultListener.class); manager.prefetchDeltaSignerInfo( getSlowFailingProvider(ticker, EASY_TICKS), getRealSignerId(), getFakeWaveletName(CertificateManagerImplTest.DOMAIN), getHashedVersion(), failListener); verifyZeroInteractions(failListener); // This will succeed immediately SignerInfoPrefetchResultListener successListener = mock(SignerInfoPrefetchResultListener.class); manager.prefetchDeltaSignerInfo( getSuccessfulProvider(), getRealSignerId(), getFakeWaveletName(OTHER_DOMAIN), getHashedVersion(), successListener); verify(successListener).onSuccess(Certificates.getRealSignerInfo().toProtoBuf()); verify(failListener).onSuccess(Certificates.getRealSignerInfo().toProtoBuf()); // The failing listener shouldn't do anything, even after the ticks ticker.tick(EASY_TICKS); verifyNoMoreInteractions(failListener); verifyNoMoreInteractions(successListener); }
@Test public void deleteById() throws NotFoundException { when(redisTemplateMock.boundHashOps(CONTACT_KEY)).thenReturn(boundHashOperationsMock); when(redisTemplateMock.opsForSet()).thenReturn(setOperationsMock); when(setOperationsMock.isMember(RedisContactService.KEY_CONTACT_SET, CONTACT_KEY)) .thenReturn(true); initGetHashOperationsForContact(CONTACT_ID); Contact deleted = service.deleteById(CONTACT_ID); verify(redisTemplateMock, times(2)).boundHashOps(CONTACT_KEY); verifyThatContactWasGet(); verifyThatContactWasDeleted(); verify(redisTemplateMock, times(2)).opsForSet(); verify(setOperationsMock, times(1)).isMember(RedisContactService.KEY_CONTACT_SET, CONTACT_KEY); verify(setOperationsMock, times(1)).remove(RedisContactService.KEY_CONTACT_SET, CONTACT_KEY); verifyNoMoreInteractions(setOperationsMock); verifyNoMoreInteractions(boundHashOperationsMock, redisTemplateMock); verifyZeroInteractions(contactIdCounterMock); assertContact(CONTACT_ID, deleted); }
@Test public void testSetup() throws Exception { // tell the method story as it happens: mock or create dependencies and configure // those dependencies to get the method under test to completion DatabaseType databaseType = DatabaseType.Postgres; EntityManager mockEntityManager = mock(EntityManager.class); Session mockCassandraSession = mock(Session.class); DataMigratorConfiguration mockConfig = PowerMockito.mock(DataMigratorConfiguration.class); PowerMockito.whenNew(DataMigratorConfiguration.class) .withArguments(eq(mockEntityManager), eq(mockCassandraSession), eq(databaseType), eq(false)) .thenReturn(mockConfig); // create object to test and inject required dependencies DataMigrator objectUnderTest = new DataMigrator(mockEntityManager, mockCassandraSession, databaseType); // run code under test objectUnderTest.runRawDataMigration(false); objectUnderTest.runRawDataMigration(true); objectUnderTest.run1HAggregateDataMigration(false); objectUnderTest.run1HAggregateDataMigration(true); objectUnderTest.run6HAggregateDataMigration(false); objectUnderTest.run6HAggregateDataMigration(true); objectUnderTest.run1DAggregateDataMigration(false); objectUnderTest.run1DAggregateDataMigration(true); // verify the results (assert and mock verification) PowerMockito.verifyNew(DataMigratorConfiguration.class) .withArguments( eq(mockEntityManager), eq(mockCassandraSession), eq(databaseType), eq(false)); PowerMockito.verifyPrivate(mockConfig, times(2)).invoke("setRunRawDataMigration", true); PowerMockito.verifyPrivate(mockConfig, times(1)).invoke("setRunRawDataMigration", false); PowerMockito.verifyPrivate(mockConfig, times(2)).invoke("setRun1HAggregateDataMigration", true); PowerMockito.verifyPrivate(mockConfig, times(1)) .invoke("setRun1HAggregateDataMigration", false); PowerMockito.verifyPrivate(mockConfig, times(2)).invoke("setRun6HAggregateDataMigration", true); PowerMockito.verifyPrivate(mockConfig, times(1)) .invoke("setRun6HAggregateDataMigration", false); PowerMockito.verifyPrivate(mockConfig, times(2)).invoke("setRun1DAggregateDataMigration", true); PowerMockito.verifyPrivate(mockConfig, times(1)) .invoke("setRun1DAggregateDataMigration", false); PowerMockito.verifyPrivate(mockConfig, times(1)) .invoke("setDeleteDataImmediatelyAfterMigration", false); PowerMockito.verifyPrivate(mockConfig, times(1)) .invoke("setDeleteAllDataAtEndOfMigration", false); PowerMockito.verifyNoMoreInteractions(mockConfig); verifyNoMoreInteractions(mockEntityManager); verifyNoMoreInteractions(mockCassandraSession); }
@After public void tearDown() { verifyNoMoreInteractions(mockClient); verifyNoMoreInteractions(mockTables); verifyNoMoreInteractions(mockTablesGet); verifyNoMoreInteractions(mockTabledata); verifyNoMoreInteractions(mockTabledataList); }
@Test public void testClose() throws Exception { classFileLocator.close(); verify(foo).close(); verifyNoMoreInteractions(foo); verify(bar).close(); verifyNoMoreInteractions(bar); }
@Test public void canProcessMultipleLinksWhenCommandNotKnownOnLink2() throws Exception { final String receiver = "*****@*****.**"; createMailUser(receiver, "loginIdReceiver", "secretOfReceiver"); String validSender = "*****@*****.**"; sendMailTo(receiver).from(validSender).withSubject(anySubject()).andText("usedScenario"); Link link1 = Links.getLink(new URI(mockURI + "?num=1&foo=bar")); Link link2 = Links.getLink(new URI(mockURI + "?num=2&foo=bar")); final String to1 = makeURI( mockURI, newMapBuilder() .put("linkparams", encode("num=1&foo=bar")) .put("validfroms", validSender) .put("scenario.usedScenario", "D11=true;A12=11") .build()); final String to2 = makeURI( mockURI, newMapBuilder() .put("linkparams", encode("num=2&foo=bar")) .put("validfroms", validSender) .build()); try { CamelContext context = new DefaultCamelContext(); context.addRoutes( new RouteBuilder() { @Override public void configure() { from(localImap(receiver)) .multicast() .setAggregationStrategy(new UseOriginalAggregationStrategy()) .to(to1, to2); } }); context.start(); waitUntilMailWasFetched(); context.stop(); Link mock1 = getMock(link1); verify(mock1).switchDigitalPin(digitalPin(11), true); verify(mock1).switchAnalogPin(analogPin(12), 11); verify(mock1).close(); verifyNoMoreInteractions(mock1); Link mock2 = getMock(link2); verify(mock2).close(); verifyNoMoreInteractions(mock2); } finally { link1.close(); link2.close(); } }
@Test public void updateAuthenticatedContributorProfile() { AuthenticationUtilService tested = getTested(); // case - nobody is authenticated { Mockito.when(tested.httpRequest.getUserPrincipal()).thenReturn(null); Assert.assertFalse(tested.updateAuthenticatedContributorProfile()); Mockito.verifyZeroInteractions(tested.contributorProfileService); } Principal p = Mockito.mock(Principal.class); // case - provider is authenticated { Mockito.reset(tested.contributorProfileService, tested.httpRequest); Mockito.when(tested.httpRequest.getUserPrincipal()).thenReturn(p); Mockito.when(tested.httpRequest.isUserInRole(Role.PROVIDER)).thenReturn(true); Assert.assertFalse(tested.updateAuthenticatedContributorProfile()); Mockito.verifyZeroInteractions(tested.contributorProfileService); } // case - contributor is authenticated but username not in principal { Mockito.reset(tested.contributorProfileService, tested.httpRequest, p); Mockito.when(tested.httpRequest.getUserPrincipal()).thenReturn(p); Mockito.when(tested.httpRequest.isUserInRole(Role.CONTRIBUTOR)).thenReturn(true); Assert.assertFalse(tested.updateAuthenticatedContributorProfile()); Mockito.verifyZeroInteractions(tested.contributorProfileService); Mockito.verify(p).getName(); } // case - contributor is authenticated, username is in principal { p = new ContributorPrincipal("uname"); Mockito.reset(tested.contributorProfileService, tested.httpRequest); Mockito.when(tested.httpRequest.getUserPrincipal()).thenReturn(p); Mockito.when(tested.httpRequest.isUserInRole(Role.CONTRIBUTOR)).thenReturn(true); Assert.assertTrue(tested.updateAuthenticatedContributorProfile()); Mockito.verify(tested.contributorProfileService) .createOrUpdateProfile( ContributorProfileService.FIELD_TSC_JBOSSORG_USERNAME, "uname", false); Mockito.verifyNoMoreInteractions(tested.contributorProfileService); } // case - contributor is authenticated, unsupported type of principal { p = Mockito.mock(Principal.class); Mockito.reset(tested.contributorProfileService, tested.httpRequest); Mockito.when(tested.httpRequest.getUserPrincipal()).thenReturn(p); Mockito.when(tested.httpRequest.isUserInRole(Role.CONTRIBUTOR)).thenReturn(true); Assert.assertFalse(tested.updateAuthenticatedContributorProfile()); Mockito.verifyNoMoreInteractions(tested.contributorProfileService); } }
@Test public void shouldNotSaveAnythingIfTheDrishtiResponseStatusIsFailure() throws Exception { setupActions(failure, asList(actionForDeleteAlert("Case X", "ANC 1", "0"))); assertEquals(fetchedFailed, service.fetchNewActions()); verify(drishtiService).fetchNewActions("ANM X", "1234"); verifyNoMoreInteractions(drishtiService); verifyNoMoreInteractions(allAlerts); }
@Test public void testNoGroupCollapse() throws IOException { when(rb.grouping()).thenReturn(true); when(params.getBool(GroupCollapseParams.GROUP_COLLAPSE, false)).thenReturn(false); component.process(rb); verify(rb).grouping(); verify(params).getBool(GroupCollapseParams.GROUP_COLLAPSE, false); verifyNoMoreInteractions(rb); verifyNoMoreInteractions(params); }