Java Code Examples for org.mockito.Mockito
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project addressbook-sample-mongodb, under directory /web-ui/src/test/java/nl/enovation/addressbook/cqrs/webui/controllers/.
Source file: ContactsControllerIntegrationTest.java

@Before public void setUp(){ MockitoAnnotations.initMocks(this); Mockito.when(mockBindingResult.hasErrors()).thenReturn(false); controller=new ContactsController(contactQueryRepositoryImpl,commandBus); contactEntry=new ContactEntry(); contactEntry.setFirstName("Foo"); contactEntry.setLastName("Bar"); contactEntry.setIdentifier(new UUIDAggregateIdentifier().asString()); }
Example 2
From project atunit, under directory /atunit-mockito/src/main/java/atunit/mockito/.
Source file: MockitoFramework.java

public Map<Field,Object> getValues(Field[] fields) throws Exception { Map<Field,Object> result=new HashMap<Field,Object>(); for ( Field field : fields) { if (field.getAnnotation(Mock.class) != null || field.getAnnotation(Stub.class) != null) result.put(field,Mockito.mock(field.getType())); } return result; }
Example 3
From project AirCastingAndroidClient, under directory /src/test/java/pl/llp/aircasting/helper/.
Source file: LocationHelperTest.java

@Test public void shouldNotBeTrickedIntoThinkingItNedNotStop(){ locationHelper.stop(); reset(locationHelper.locationManager); locationHelper.start(); locationHelper.stop(); verify(locationHelper.locationManager,times(1)).removeUpdates(Mockito.any(LocationListener.class)); }
Example 4
From project alfredo, under directory /alfredo/src/test/java/com/cloudera/alfredo/client/.
Source file: TestAuthenticatedURL.java

public void testInjectToken() throws Exception { HttpURLConnection conn=Mockito.mock(HttpURLConnection.class); AuthenticatedURL.Token token=new AuthenticatedURL.Token(); token.set("foo"); AuthenticatedURL.injectToken(conn,token); Mockito.verify(conn).addRequestProperty(Mockito.eq("Cookie"),Mockito.anyString()); }
Example 5
From project android-sdk, under directory /src/test/java/com/mobeelizer/mobile/android/.
Source file: MobeelizerDataFileServiceTest.java

@Test @SuppressWarnings("unchecked") public void shouldProcessInputFile() throws Exception { File file=mock(File.class); FileInputStream fileStream=mock(FileInputStream.class); MobeelizerInputData inputData=mock(MobeelizerInputData.class); Iterable<MobeelizerJsonEntity> inputDataIterable=mock(Iterable.class); Iterator<MobeelizerJsonEntity> inputDataIterator=mock(Iterator.class); when(inputData.getInputData()).thenReturn(inputDataIterable); when(inputDataIterable.iterator()).thenReturn(inputDataIterator); PowerMockito.whenNew(FileInputStream.class).withArguments(file).thenReturn(fileStream); PowerMockito.whenNew(MobeelizerInputData.class).withArguments(eq(fileStream),any(File.class)).thenReturn(inputData); when(database.updateEntitiesFromSync(inputDataIterator,true)).thenReturn(true); MobeelizerOperationError result=dataFileService.processInputFile(file,true); InOrder order=Mockito.inOrder(inputData,database,fileService); order.verify(fileService).addFilesFromSync(anyList(),any(MobeelizerInputData.class)); order.verify(database).updateEntitiesFromSync(inputDataIterator,true); order.verify(fileService).deleteFilesFromSync(anyList()); order.verify(inputData).close(); assertNull(result); }
Example 6
From project androidannotations, under directory /AndroidAnnotations/functional-test-1-5-tests/src/test/java/com/googlecode/androidannotations/test15/rest/.
Source file: MyServiceTest.java

@Test public void can_override_root_url(){ MyService_ myService=new MyService_(); RestTemplate restTemplate=mock(RestTemplate.class); myService.setRestTemplate(restTemplate); myService.setRootUrl("http://newRootUrl"); myService.removeEvent(42); verify(restTemplate).exchange(startsWith("http://newRootUrl"),Mockito.<HttpMethod>any(),Mockito.<HttpEntity<?>>any(),Mockito.<Class<Object>>any(),Mockito.<Map<String,?>>any()); }
Example 7
From project any23, under directory /plugins/office-scraper/src/test/java/org/apache/any23/plugin/officescraper/.
Source file: ExcelExtractorTest.java

private void processFile(String resource) throws IOException, ExtractionException, TripleHandlerException { final ExtractionParameters extractionParameters=ExtractionParameters.newDefault(); final ExtractionContext extractionContext=new ExtractionContext(extractor.getDescription().getExtractorName(),RDFUtils.uri("file://" + resource)); final InputStream is=this.getClass().getResourceAsStream(resource); final CompositeTripleHandler compositeTripleHandler=new CompositeTripleHandler(); final TripleHandler verifierTripleHandler=Mockito.mock(TripleHandler.class); compositeTripleHandler.addChild(verifierTripleHandler); final CountingTripleHandler countingTripleHandler=new CountingTripleHandler(); compositeTripleHandler.addChild(countingTripleHandler); final ByteArrayOutputStream out=new ByteArrayOutputStream(); compositeTripleHandler.addChild(new NTriplesWriter(out)); final ExtractionResult extractionResult=new ExtractionResultImpl(extractionContext,extractor,compositeTripleHandler); extractor.run(extractionParameters,extractionContext,is,extractionResult); compositeTripleHandler.close(); logger.info(out.toString()); verifyPredicateOccurrence(verifierTripleHandler,Excel.getInstance().containsSheet,2); verifyPredicateOccurrence(verifierTripleHandler,Excel.getInstance().containsRow,6); verifyPredicateOccurrence(verifierTripleHandler,Excel.getInstance().containsCell,18); verifyTypeOccurrence(verifierTripleHandler,Excel.getInstance().sheet,2); verifyTypeOccurrence(verifierTripleHandler,Excel.getInstance().row,6); verifyTypeOccurrence(verifierTripleHandler,Excel.getInstance().cell,18); }
Example 8
From project aranea, under directory /core/src/test/java/no/dusken/aranea/service/.
Source file: TestStoreImageService.java

@Test public void testMakeAndGetImageFile() throws IOException { File originalFile=new File("src/test/resources/testImage.jpg"); assertTrue("Could not read test image",originalFile.exists() && originalFile.canRead()); File file=File.createTempFile("tempImage",""); FileUtils.copyFile(originalFile,file); assertTrue("Could not read copied image",file.exists() && file.canRead()); String hash=MD5.asHex(MD5.getHash(file)); Mockito.when(imageService.getImageByHash(hash)).thenReturn(null); Mockito.when(imageService.saveOrUpdate((Image)anyObject())).thenAnswer(new Answer<Image>(){ public Image answer( InvocationOnMock invocation) throws Throwable { return (Image)invocation.getArguments()[0]; } } ); Image image=storeImageService.createImage(file); assertTrue("The image was not removed",!file.exists()); File newFile=imageUtils.getImageFile(image); String newHash=MD5.asHex(MD5.getHash(newFile)); assertEquals("Did not get the unchanged file",hash,newHash); assertEquals("Image object has wrong hash",hash,image.getHash()); assertEquals("Image has wrong height",45,image.getHeight().intValue()); assertEquals("Image has wrong width",45,image.getWidth().intValue()); assertEquals("Image has wrong ratio",(double)1,image.getRatio()); file.delete(); newFile.delete(); }
Example 9
From project Arecibo, under directory /dashboard/src/test/java/com/ning/arecibo/dashboard/config/.
Source file: TestCustomGroupsManager.java

@Test(groups="fast") public void testCustomGroupsConfiguration() throws Exception { final String configPath=System.getProperty("java.io.tmpdir") + "/TestCustomGroupsManager-" + System.currentTimeMillis(); final String groupsConfigurationString="" + "[\n" + " {\n"+ " \"name\":\"JVM\",\n"+ " \"kinds\":[\n"+ " {\n"+ " \"eventCategory\":\"JVMMemory\",\n"+ " \"sampleKinds\":[\"heapUsed\",\"nonHeapUsed\"]\n"+ " },\n"+ " {\n"+ " \"eventCategory\":\"CMSOldGen\",\n"+ " \"sampleKinds\":[\"memoryPoolUsed\"]\n"+ " },\n"+ " {\n"+ " \"eventCategory\":\"CMSPermGen\",\n"+ " \"sampleKinds\":[\"memoryPoolUsed\"]\n"+ " },\n"+ " {\n"+ " \"eventCategory\":\"CodeCache\",\n"+ " \"sampleKinds\":[\"memoryPoolUsed\"]\n"+ " },\n"+ " {\n"+ " \"eventCategory\":\"ParEdenSpace\",\n"+ " \"sampleKinds\":[\"memoryPoolUsed\"]\n"+ " },\n"+ " {\n"+ " \"eventCategory\":\"ParSurvivorSpace\",\n"+ " \"sampleKinds\":[\"memoryPoolUsed\"]\n"+ " },\n"+ " {\n"+ " \"eventCategory\":\"ConcurrentMarkSweepGC\",\n"+ " \"sampleKinds\":[\"garbageCollectionRate\"]\n"+ " },\n"+ " {\n"+ " \"eventCategory\":\"ParNewGC\",\n"+ " \"sampleKinds\":[\"garbageCollectionRate\"]\n"+ " },\n"+ " {\n"+ " \"eventCategory\":\"Threading\",\n"+ " \"sampleKinds\":[\"threadCount\"]\n"+ " },\n"+ " {\n"+ " \"eventCategory\":\"JVMOperatingSystemPerZone\",\n"+ " \"sampleKinds\":[\"ProcessCpuTime\"]\n"+ " }\n"+ " ]\n"+ " }\n"+ "]"; Files.write(groupsConfigurationString,new File(configPath),Charsets.UTF_8); final DashboardConfig config=Mockito.mock(DashboardConfig.class); Mockito.when(config.getCustomGroupsFile()).thenReturn(configPath); final CustomGroupsManager manager=new CustomGroupsManager(config); final List<CustomGroup> configuration=manager.getCustomGroups(); Assert.assertEquals(configuration.size(),1); final CustomGroup group=configuration.get(0); Assert.assertEquals(group.getName(),"JVM"); Assert.assertEquals(group.getKinds().size(),10); Assert.assertEquals(group.getKinds().get(0).getEventCategory(),"JVMMemory"); Assert.assertEquals(group.getKinds().get(0).getSampleKinds().size(),2); }
Example 10
From project arquillian-core, under directory /container/impl-base/src/test/java/org/jboss/arquillian/container/impl/client/container/.
Source file: ContainerRegistryCreatorTestCase.java

@Test(expected=IllegalStateException.class) public void shouldThrowExceptionIfMultipleDeployableContainersFoundOnClassapth(){ Mockito.when(serviceLoader.onlyOne(DeployableContainer.class)).thenThrow(new IllegalStateException("Multiple service implementations found for ...")); try { fire(Descriptors.create(ArquillianDescriptor.class)); } catch ( IllegalStateException e) { Assert.assertTrue(e.getMessage().startsWith("Could not add a default container")); throw e; } }
Example 11
From project arquillian-extension-android, under directory /android-impl/src/test/java/org/jboss/arquillian/android/enricher/.
Source file: AndroidDeviceEnricherTestCase.java

@org.junit.Before public void setMocks(){ ArquillianDescriptor desc=Descriptors.create(ArquillianDescriptor.class); TestEnricher enricher=new ArquillianResourceTestEnricher(); enricher=injector.get().inject(enricher); ResourceProvider provider=new AndroidDeviceResourceProvider(); provider=injector.get().inject(provider); Mockito.when(serviceLoader.all(TestEnricher.class)).thenReturn(Arrays.asList(enricher)); Mockito.when(serviceLoader.all(ResourceProvider.class)).thenReturn(Arrays.asList(provider)); Mockito.when(runningDevice.getAvdName()).thenReturn("mockedAndroid"); bind(ApplicationScoped.class,ServiceLoader.class,serviceLoader); bind(ApplicationScoped.class,ArquillianDescriptor.class,desc); bind(SuiteScoped.class,AndroidDevice.class,runningDevice); }
Example 12
From project arquillian-extension-drone, under directory /drone-impl/src/test/java/org/jboss/arquillian/drone/impl/.
Source file: DestroyerTestCase.java

@SuppressWarnings("rawtypes") @org.junit.Before public void setMocks(){ ArquillianDescriptor desc=Descriptors.create(ArquillianDescriptor.class).extension("mockdrone").property("field","foobar"); TestEnricher testEnricher=new DroneTestEnricher(); bind(ApplicationScoped.class,ServiceLoader.class,serviceLoader); bind(ApplicationScoped.class,ArquillianDescriptor.class,desc); Mockito.when(serviceLoader.all(Configurator.class)).thenReturn(Arrays.<Configurator>asList(new MockDroneFactory())); Mockito.when(serviceLoader.all(Instantiator.class)).thenReturn(Arrays.<Instantiator>asList(new MockDroneFactory())); Mockito.when(serviceLoader.all(Destructor.class)).thenReturn(Arrays.<Destructor>asList(new MockDroneFactory())); Mockito.when(serviceLoader.onlyOne(TestEnricher.class)).thenReturn(testEnricher); }
Example 13
From project arquillian-extension-warp, under directory /impl/src/test/java/org/jboss/arquillian/warp/impl/client/separation/.
Source file: TestPreventingClassLoader.java

@SeparatedClassPath public static JavaArchive[] archive(){ JavaArchive archive=ShrinkWrap.create(JavaArchive.class).addClasses(PreventingClassLoader.class,ClassLoaderUtils.class); JavaArchive mockito=ShrinkWrapUtils.getJavaArchiveFromClass(Mockito.class); JavaArchive junit=ShrinkWrapUtils.getJavaArchiveFromClass(Assert.class); return new JavaArchive[]{archive,mockito,junit}; }
Example 14
From project arquillian-graphene, under directory /graphene-webdriver/graphene-webdriver-drone/src/test/java/org/jboss/arquillian/ajocado/drone/factory/.
Source file: AbstractDroneTestCase.java

@Before public void initialize(){ descriptor=Descriptors.create(ArquillianDescriptor.class); serviceLoader=Mockito.mock(ServiceLoader.class); getManager().bind(ApplicationScoped.class,ServiceLoader.class,serviceLoader); getManager().bind(ApplicationScoped.class,ArquillianDescriptor.class,descriptor); }
Example 15
From project arquillian-showcase, under directory /extensions/autodiscover/src/main/java/org/jboss/arquillian/showcase/extension/autodiscover/container/.
Source file: Enricher.java

private void enrichFields(Object testCase){ List<Field> mockFields=ReflectionHelper.getFieldsWithAnnotation(testCase.getClass(),Mock.class); for ( Field mockField : mockFields) { try { Object mocked=Mockito.mock(mockField.getType()); if (!mockField.isAccessible()) { mockField.setAccessible(true); } mockField.set(testCase,mocked); } catch ( Exception e) { throw new RuntimeException("Could not inject mocked object on field " + mockField,e); } } }
Example 16
From project arquillian_deprecated, under directory /extensions/drone/src/test/java/org/jboss/arquillian/drone/factory/.
Source file: PrecedenceTestCase.java

@Test @SuppressWarnings("rawtypes") public void testPrecedence() throws Exception { Mockito.when(serviceLoader.all(Configurator.class)).thenReturn(Arrays.<Configurator>asList(new DefaultSeleniumFactory(),new WebDriverFactory(),new MockConfigurator())); manager.fire(new BeforeSuite()); DroneRegistry registry=manager.getContext(SuiteContext.class).getObjectStore().get(DroneRegistry.class); Assert.assertNotNull("Drone registry was created in the context",registry); Assert.assertTrue("Configurator is of mock type",registry.getConfiguratorFor(DefaultSelenium.class) instanceof MockConfigurator); manager.fire(new BeforeClass(this.getClass())); DroneContext context=manager.getContext(ClassContext.class).getObjectStore().get(DroneContext.class); Assert.assertNotNull("Drone object holder was created in the context",context); SeleniumConfiguration configuration=context.get(SeleniumConfiguration.class); Assert.assertEquals("SeleniumConfiguration has *testbrowser set as browser","*testbrowser",configuration.getBrowser()); }
Example 17
From project Axon-trader, under directory /orders/src/test/java/org/axonframework/samples/trader/orders/command/.
Source file: PortfolioManagementUserListenerTest.java

@Test public void checkPortfolioCreationAfterUserCreated(){ CommandBus commandBus=Mockito.mock(CommandBus.class); PortfolioManagementUserListener listener=new PortfolioManagementUserListener(); listener.setCommandBus(commandBus); UserId userIdentifier=new UserId(); UserCreatedEvent event=new UserCreatedEvent(userIdentifier,"Test","testuser","testpassword"); listener.createNewPortfolioWhenUserIsCreated(event); Mockito.verify(commandBus).dispatch(Matchers.argThat(new GenericCommandMessageMatcher(userIdentifier))); }
Example 18
From project BuilderGen, under directory /buildergen/src/test/java/info/piwai/buildergen/generation/.
Source file: ResourceCodeWriterTest.java

/** * This test is just for the fun of using Mockito. It does not really test the external behavior of the method. */ @Test public void usesFilerToOpenStream() throws IOException { Filer filer=mock(Filer.class); FileObject fileObject=mock(FileObject.class); when(filer.createResource(Mockito.<Location>any(),anyString(),anyString())).thenReturn(fileObject); OutputStream expectedOS=mock(OutputStream.class); when(fileObject.openOutputStream()).thenReturn(expectedOS); ResourceCodeWriter resourceCodeWriter=new ResourceCodeWriter(filer); JPackage jPackage=new JCodeModel()._package("some.package"); OutputStream resultingOS=resourceCodeWriter.openBinary(jPackage,null); assertSame(expectedOS,resultingOS); }
Example 19
From project candlepin, under directory /src/test/java/org/candlepin/controller/.
Source file: PoolManagerFunctionalTest.java

@Test public void testRegenerateEntitlementCertificatesWithNoEntitlement(){ reset(this.eventSink); poolManager.regenerateEntitlementCertificates(childVirtSystem,true); assertEquals(0,collectEntitlementCertIds(this.childVirtSystem).size()); Mockito.verifyZeroInteractions(this.eventSink); }
Example 20
From project Carolina-Digital-Repository, under directory /persistence/src/test/java/edu/unc/lib/dl/services/.
Source file: DigitalObjectManagerImplTest.java

/** * Test method for {@link edu.unc.lib.dl.services.BatchIngestService#ingestBatchNow(java.io.File)}. */ @Test public void testSingleIngestNow(){ try { reset(this.managementClient); PersonAgent user=new PersonAgent(new PID("test:person"),"TestyTess","testonyen"); DepositRecord record=new DepositRecord(user,user,DepositMethod.Unspecified); PID container=new PID("test:container"); SingleFolderSIP sip=new SingleFolderSIP(); sip.setContainerPID(container); sip.setSlug("testslug"); when(this.managementClient.pollForObject(any(PID.class),Mockito.anyInt(),Mockito.anyInt())).thenReturn(true); List<String> personrow=new ArrayList<String>(); personrow.add(user.getPID().getURI()); personrow.add(user.getName()); personrow.add(user.getOnyen()); List<List<String>> answer=new ArrayList<List<String>>(); answer.add(personrow); when(this.tripleStoreQueryService.queryResourceIndex(any(String.class))).thenReturn(answer); when(this.tripleStoreQueryService.lookupRepositoryPath(eq(container))).thenReturn("/test/container/path"); when(this.tripleStoreQueryService.fetchByRepositoryPath(eq("/test/container/path"))).thenReturn(container); when(this.tripleStoreQueryService.verify(any(PID.class))).thenReturn(container); when(this.managementClient.upload(any(File.class))).thenReturn("upload:19238"); when(this.managementClient.upload(any(Document.class))).thenReturn("upload:19238"); ArrayList<URI> ans=new ArrayList<URI>(); ans.add(ContentModelHelper.Model.CONTAINER.getURI()); when(this.tripleStoreQueryService.lookupContentModels(eq(container))).thenReturn(ans); digitalObjectManagerImpl.addWhileBlocking(sip,record); verify(this.managementClient,times(2)).ingest(any(Document.class),any(Format.class),any(String.class)); } catch ( Exception e) { e.printStackTrace(); throw new Error(e); } }
Example 21
From project chargifyService, under directory /src/test/java/com/mondora/chargify/mock/.
Source file: FailingChargify.java

@Override protected HttpResponse executeHttpMethod(HttpRequestBase method) throws IOException { randomizer.setSeed(System.currentTimeMillis()); final int code=codes[randomizer.nextInt(codes.length)]; final String errorMessage="Simulated error " + code; HttpResponse response=Mockito.mock(HttpResponse.class); Mockito.stub(response.getStatusLine()).toReturn(new StatusLine(){ @Override public ProtocolVersion getProtocolVersion(){ return null; } @Override public int getStatusCode(){ return code; } @Override public String getReasonPhrase(){ return errorMessage; } } ); return response; }
Example 22
From project codjo-control, under directory /codjo-control-server/src/test/java/net/codjo/control/server/plugin/.
Source file: ControlServerPluginTest.java

@Before public void setUp() throws Exception { fixture.doSetUp(); WorkflowServerPlugin workflowServerPluginMock=mock(WorkflowServerPlugin.class); WorkflowServerPluginConfiguration pluginConfigurationMock=mock(WorkflowServerPluginConfiguration.class); when(workflowServerPluginMock.getConfiguration()).thenReturn(pluginConfigurationMock); plugin=new ControlServerPlugin(workflowServerPluginMock,new InternationalizationPlugin(),new MadServerPluginMock(new LogString("madServerPlugin",log)),new ServerCoreMock(new LogString("core",log),fixture)); log.assertAndClear("madServerPluginConfiguration.addHandlerCommand(SelectAllQuarantineColumnsFromTableHandler)"); verify(pluginConfigurationMock).registerJobBuilder(Mockito.<JobBuilder>anyObject()); }
Example 23
From project codjo-imports, under directory /codjo-imports-server/src/test/java/net/codjo/imports/server/plugin/.
Source file: ImportJobRequestHandlerTest.java

@Before public void setUp() throws Exception { ConnectionPoolMock connectionPoolMock=new ConnectionPoolMock(log); connectionPoolMock.mockGetConnection(connectionMock); stub(jdbcServerOperationsMock.getPool(Mockito.<UserId>anyObject())).toReturn(connectionPoolMock); importJobRequestHandler=new ImportJobRequestHandler(jdbcServerOperationsMock,new ImportJobDaoMock()); }
Example 24
From project codjo-segmentation, under directory /codjo-segmentation-gui/src/test/java/net/codjo/segmentation/gui/plugin/.
Source file: SegmentationGuiPluginTest.java

@Override public void setUp() throws Exception { RequestIdManager.getInstance().reset(); PreferenceFactory.initFactory(); initServerWrapperMock(); initGuiContextMock(); initGuiConfigurationMock(); initMadGuiPluginMock(); segmentationGuiPlugin=new SegmentationGuiPlugin(Mockito.mock(ApplicationCore.class),madGuiPlugin,new WorkflowGuiPlugin()); }
Example 25
From project collector, under directory /src/test/java/com/ning/metrics/collector/guice/.
Source file: TestHealthChecksModule.java

@Test(groups="fast") public void testConfigure(){ try { final Injector injector=Guice.createInjector(new AbstractModule(){ @Override protected void configure(){ bind(FileSystemAccess.class).toInstance(Mockito.mock(FileSystemAccess.class)); bind(EventQueueProcessor.class).toInstance(Mockito.mock(EventQueueProcessorImpl.class)); bind(GlobalEventQueueStats.class).toInstance(Mockito.mock(GlobalEventQueueStats.class)); bind(EventSpoolDispatcher.class).toInstance(Mockito.mock(EventSpoolDispatcher.class)); bind(PersistentWriterFactory.class).toInstance(Mockito.mock(PersistentWriterFactory.class)); bind(WriterStats.class).toInstance(Mockito.mock(WriterStats.class)); bind(CollectorConfig.class).toInstance(Mockito.mock(CollectorConfig.class)); } } ,new HealthChecksModule()); Assert.assertNotNull(injector.getBinding(AdminServlet.class)); Assert.assertNotNull(injector.getBinding(HadoopHealthCheck.class)); Assert.assertNotNull(injector.getBinding(RealtimeHealthCheck.class)); Assert.assertNotNull(injector.getBinding(WriterHealthCheck.class)); } catch ( Exception e) { Assert.fail(e.getMessage()); } }
Example 26
From project com.cedarsoft.serialization, under directory /serialization/src/test/java/com/cedarsoft/serialization/.
Source file: SerializingStrategySupportTest.java

@Test public void testVersionMappings() throws Exception { new MockitoTemplate(){ @Mock private SerializingStrategy<Integer,StringBuilder,String,IOException> strategy1; @Mock private SerializingStrategy<Integer,StringBuilder,String,IOException> strategy2; @Override protected void stub() throws Exception { when(strategy1.getFormatVersionRange()).thenReturn(VersionRange.single(0,0,1)); when(strategy2.getFormatVersionRange()).thenReturn(VersionRange.single(0,0,2)); when(strategy1.getId()).thenReturn("id1"); when(strategy2.getId()).thenReturn("id2"); } @Override protected void execute() throws Exception { support.addStrategy(strategy1).map(1,0,0).toDelegateVersion(0,0,1); support.addStrategy(strategy2).map(1,0,0).toDelegateVersion(0,0,2); assertTrue(support.verify()); assertEquals(1,support.getVersionMappings().getMappedVersions().size()); assertEquals(Version.valueOf(0,0,1),support.resolveVersion(strategy1,Version.valueOf(1,0,0))); assertEquals(Version.valueOf(0,0,2),support.resolveVersion(strategy2,Version.valueOf(1,0,0))); } @Override protected void verifyMocks() throws Exception { Mockito.verify(strategy1).getFormatVersionRange(); Mockito.verifyNoMoreInteractions(strategy1); Mockito.verify(strategy2).getFormatVersionRange(); Mockito.verifyNoMoreInteractions(strategy2); } } .run(); }
Example 27
From project core_1, under directory /admin/src/test/java/org/switchyard/admin/base/.
Source file: MessageMetricsCollectionTest.java

@Test public void testOperationLevelCollection(){ Exchange ex=createMock(); defaultExpectations(ex); Mockito.when(ex.getContract().getProviderOperation().getName()).thenReturn(OPERATION_NAME); _builder.notify(new ExchangeCompletionEvent(ex)); assertEquals(1,_switchYard.getMessageMetrics().getSuccessCount()); assertEquals(10.0,_switchYard.getMessageMetrics().getAverageProcessingTime(),0); ComponentService componentService=_switchYard.getApplication(TEST_APP).getComponentService(TEST_PROMOTED_SERVICE); assertEquals(10.0,componentService.getMessageMetrics().getAverageProcessingTime(),0); assertEquals(10.0,componentService.getServiceOperation(OPERATION_NAME).getMessageMetrics().getAverageProcessingTime(),0); }
Example 28
From project core_4, under directory /impl/src/test/java/org/richfaces/resource/.
Source file: ResourceFactoryImplStaticResourcesTest.java

private Resource resource(String library,String name,final Location location){ Resource resource=Mockito.mock(Resource.class); when(resource.getLibraryName()).thenReturn(library); when(resource.getResourceName()).thenReturn(name); when(resource.getRequestPath()).thenAnswer(new Answer<String>(){ @Override public String answer( InvocationOnMock invocation) throws Throwable { return location.getRequestPath(); } } ); return resource; }
Example 29
From project curator, under directory /curator-client/src/test/java/com/netflix/curator/.
Source file: BasicTests.java

@Test public void testFactory() throws Exception { final ZooKeeper mockZookeeper=Mockito.mock(ZooKeeper.class); ZookeeperFactory zookeeperFactory=new ZookeeperFactory(){ @Override public ZooKeeper newZooKeeper( String connectString, int sessionTimeout, Watcher watcher) throws Exception { return mockZookeeper; } } ; CuratorZookeeperClient client=new CuratorZookeeperClient(zookeeperFactory,new FixedEnsembleProvider(server.getConnectString()),10000,10000,null,new RetryOneTime(1)); client.start(); Assert.assertEquals(client.getZooKeeper(),mockZookeeper); }
Example 30
From project devTrac, under directory /src/test/com/phonegap/util/.
Source file: NetworkSuffixGeneratorTest.java

private NetworkSuffixGenerator spyOnGenerator(Boolean hasBESCoverage,Boolean hasBISCoverage,Boolean hasTCPCoverage,Boolean hasWiFiCoverage){ NetworkSuffixGenerator spy=(NetworkSuffixGenerator)Mockito.spy(generator); ((NetworkSuffixGenerator)Mockito.doReturn(hasTCPCoverage).when(spy)).hasTCPCoverage(); ((NetworkSuffixGenerator)Mockito.doReturn(hasBISCoverage).when(spy)).hasBISCoverage(); ((NetworkSuffixGenerator)Mockito.doReturn(hasBESCoverage).when(spy)).hasBESCoverage(); ((NetworkSuffixGenerator)Mockito.doReturn(hasWiFiCoverage).when(spy)).hasWiFiCoverage(); return spy; }
Example 31
From project EasySOA, under directory /easysoa-registry/easysoa-registry-rest/src/test/java/org/easysoa/rest/.
Source file: ServiceFinderTest.java

private UriInfo mockUriInfo(String uri) throws URISyntaxException { UriInfo uriInfo=Mockito.mock(UriInfo.class); Mockito.when(uriInfo.getRequestUri()).thenReturn(new URI("http://127.0.0.1:8080/nuxeo/site/easysoa/servicefinder/" + uri)); Mockito.when(uriInfo.getBaseUri()).thenReturn(new URI("http://127.0.0.1:8080/nuxeo/site/")); return uriInfo; }
Example 32
From project emite, under directory /src/test/java/com/calclab/emite/xep/chatstate/.
Source file: ChatStateTest.java

@Before public void aaCreate(){ pairChat=Mockito.mock(PairChat.class); chatStateHook=new ChatStateHook(new SimpleEventBus(),pairChat); stateHandler=new ChatStateChangedTestHandler(); chatStateHook.addChatStateChangedHandler(stateHandler); }
Example 33
From project empire-db, under directory /empire-db-codegen/src/test/java/org/apache/empire/db/codegen/util/.
Source file: DBUtilTest.java

@Test public void testCloseResultSet() throws SQLException { Logger log=Mockito.mock(Logger.class); boolean succes=DBUtil.close((ResultSet)null,log); assertTrue(succes); ResultSet rs=Mockito.mock(ResultSet.class); boolean succes2=DBUtil.close(rs,log); assertTrue(succes2); ResultSet rsFail=Mockito.mock(ResultSet.class); Exception exception=new SQLException("test"); Mockito.doThrow(exception).when(rsFail).close(); boolean succes3=DBUtil.close(rsFail,log); assertFalse(succes3); Mockito.verify(log).error("The resultset could not be closed!",exception); }
Example 34
From project eventtracker, under directory /http/src/test/java/com/ning/metrics/eventtracker/.
Source file: TestHttpJob.java

@Test(groups="fast") public void testSubmitRequest() throws Exception { final ThreadSafeAsyncHttpClient client=Mockito.mock(ThreadSafeAsyncHttpClient.class); final File file=Mockito.mock(File.class); final AsyncCompletionHandler<Response> completionHandler=Mockito.mock(AsyncResponseCompletionHandler.class); final HttpJob job=new HttpJob(client,file,completionHandler); Mockito.verify(client,Mockito.times(0)).executeRequest(file,completionHandler); job.submitRequest(); Mockito.verify(client,Mockito.times(1)).executeRequest(file,completionHandler); }
Example 35
From project fiftyfive-wicket, under directory /fiftyfive-wicket-shiro/src/main/java/fiftyfive/wicket/shiro/test/.
Source file: AbstractShiroJUnit4Tests.java

/** * Install a Mockito mock of {@link Subject} in Shiro's thread local. This causes the mockto be returned when application code (and fiftyfive-wicket-shiro code) calls {@link org.apache.shiro.SecurityUtils#getSubject() SecurityUtils.getSubject()}. */ @Before public void attachSubject(){ this.mockShiroSession=Mockito.mock(Session.class); this.mockSubject=Mockito.mock(Subject.class); Mockito.when(this.mockSubject.getSession()).thenReturn(this.mockShiroSession); this.threadState=new SubjectThreadState(this.mockSubject); this.threadState.bind(); }
Example 36
From project flexmojos, under directory /flexmojos-maven-plugin/src/test/java/net/flexmojos/oss/plugin/compiler/.
Source file: MockObject.java

@Test public void mockObject(){ List<String> a=new ArrayList<String>(Arrays.asList("a")); List<String> a1=Mockito.spy(a); when(a1.toString()).thenReturn("33"); System.out.println(a); System.out.println(a1); }
Example 37
From project Flume-Hive, under directory /src/javatest/com/cloudera/flume/agent/diskfailover/.
Source file: TestDiskFailoverDeco.java

/** * Semantically, if an exception is thrown by an internal thread, the exception should get percolated up to the appender. */ @Test public void testHandleExns() throws IOException { EventSink msnk=mock(EventSink.class); doNothing().when(msnk).open(); doNothing().when(msnk).close(); doNothing().doThrow(new IOException("foo")).doNothing().when(msnk).append(Mockito.<Event>anyObject()); doReturn(new ReportEvent("blah")).when(msnk).getReport(); Event e1=new EventImpl(new byte[0]); Event e2=new EventImpl(new byte[0]); Event e3=new EventImpl(new byte[0]); EventSource msrc=mock(EventSource.class); doNothing().when(msrc).open(); doNothing().when(msrc).close(); when(msrc.next()).thenReturn(e1).thenReturn(e2).thenReturn(e3).thenReturn(null); DiskFailoverDeco<EventSink> snk=new DiskFailoverDeco<EventSink>(msnk,FlumeNode.getInstance().getDFOManager(),new TimeTrigger(new ProcessTagger(),60000),300000); snk.open(); try { EventUtil.dumpAll(msrc,snk); snk.close(); } catch ( IOException ioe) { return; } fail("Expected IO exception to percolate to this thread"); }
Example 38
From project flume_1, under directory /flume-core/src/test/java/com/cloudera/flume/agent/diskfailover/.
Source file: TestDiskFailoverDeco.java

/** * Semantically, if an exception is thrown by an internal thread, the exception should get percolated up to the appender. * @throws InterruptedException */ @Test public void testHandleExns() throws IOException, InterruptedException { EventSink msnk=mock(EventSink.class); doNothing().when(msnk).open(); doNothing().when(msnk).close(); doNothing().doThrow(new IOException("foo")).doNothing().when(msnk).append(Mockito.<Event>anyObject()); doReturn(new ReportEvent("blah")).when(msnk).getMetrics(); Event e1=new EventImpl(new byte[0]); Event e2=new EventImpl(new byte[0]); Event e3=new EventImpl(new byte[0]); EventSource msrc=mock(EventSource.class); doNothing().when(msrc).open(); doNothing().when(msrc).close(); when(msrc.next()).thenReturn(e1).thenReturn(e2).thenReturn(e3).thenReturn(null); DiskFailoverDeco snk=new DiskFailoverDeco(msnk,LogicalNodeContext.testingContext(),FlumeNode.getInstance().getDFOManager(),new TimeTrigger(new ProcessTagger(),60000),300000); snk.open(); try { EventUtil.dumpAll(msrc,snk); snk.close(); } catch ( IOException ioe) { return; } fail("Expected IO exception to percolate to this thread"); }
Example 39
From project galaxy, under directory /test/co/paralleluniverse/galaxy/core/.
Source file: CacheTest.java

/** * When CHNGD_OWNR is received as a response to a GET, but new owner is not in cluster then re-send GET to the old owner. */ @Test public void whenGetAndCHNGD_OWNRAndNoNodeThenGETAgainIgnoreChange() throws Exception { PUT(1234L,sh(10),1,"x"); INV(1234L,sh(10)); Mockito.reset(comm); cache.runOp(new Op(GET,1234L,null)); when(cluster.getMaster(sh(20))).thenReturn(null); LineMessage msg=(LineMessage)captureMessage(); cache.receive(Message.CHNGD_OWNR(msg,1234L,sh(20),true)); verify(comm).send(argThat(equalTo(Message.GET(sh(10),1234L)))); }