public void setUp() throws Exception { super.setUp(); migrationRunnerStrategy = new OrderedMigrationRunnerStrategy(); allMigrationTasks = new ArrayList<MigrationTask>(); IMocksControl mockControl = createControl(); currentPatchInfoStore = mockControl.createMock(PatchInfoStore.class); allMigrationTasks.add(new TestRollbackableTask1()); allMigrationTasks.add(new TestRollbackableTask2()); allMigrationTasks.add(new TestRollbackableTask3()); allMigrationTasks.add(new TestRollbackableTask4()); allMigrationTasks.add(new TestRollbackableTask5()); expect(currentPatchInfoStore.getPatchLevel()).andReturn(12); mockControl.replay(); }
@Test public void testExportExisting() throws Exception { IMocksControl c = EasyMock.createControl(); RemoteServiceAdmin rsa = c.createMock(RemoteServiceAdmin.class); final EndpointListenerNotifier mockEpListenerNotifier = c.createMock(EndpointListenerNotifier.class); final ServiceReference sref = createUserService(c); expectServiceExported(c, rsa, mockEpListenerNotifier, sref, createEndpoint()); c.replay(); EndpointRepository endpointRepo = new EndpointRepository(); endpointRepo.setNotifier(mockEpListenerNotifier); ExportPolicy policy = new DefaultExportPolicy(); TopologyManagerExport exportManager = new TopologyManagerExport(endpointRepo, syncExecutor(), policy); exportManager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, sref)); exportManager.add(rsa); c.verify(); }
@Test public void testExportExistingMultipleInterfaces() throws Exception { IMocksControl c = EasyMock.createControl(); RemoteServiceAdmin rsa = c.createMock(RemoteServiceAdmin.class); final EndpointListenerNotifier mockEpListenerNotifier = c.createMock(EndpointListenerNotifier.class); List<String> exportedInterfaces = Arrays.asList("a.b.C","foo.Bar"); final ServiceReference sref = createUserService(c, exportedInterfaces); expectServiceExported(c, rsa, mockEpListenerNotifier, sref, createEndpoint()); c.replay(); EndpointRepository endpointRepo = new EndpointRepository(); endpointRepo.setNotifier(mockEpListenerNotifier); ExportPolicy policy = new DefaultExportPolicy(); TopologyManagerExport exportManager = new TopologyManagerExport(endpointRepo, syncExecutor(), policy); exportManager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, sref)); exportManager.add(rsa); c.verify(); }
@Test public void testExportExistingNoExportedInterfaces() throws Exception { IMocksControl c = EasyMock.createControl(); RemoteServiceAdmin rsa = c.createMock(RemoteServiceAdmin.class); final EndpointListenerNotifier mockEpListenerNotifier = c.createMock(EndpointListenerNotifier.class); String exportedInterfaces = ""; final ServiceReference sref = createUserService(c, exportedInterfaces); c.replay(); EndpointRepository endpointRepo = new EndpointRepository(); endpointRepo.setNotifier(mockEpListenerNotifier); ExportPolicy policy = new DefaultExportPolicy(); TopologyManagerExport exportManager = new TopologyManagerExport(endpointRepo, syncExecutor(), policy); exportManager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, sref)); exportManager.add(rsa); c.verify(); }
@Test public void testAddedRemoved() throws InvalidSyntaxException { IMocksControl c = EasyMock.createControl(); String filter = "(objectClass=My)"; BundleContext bc = createBundleContext(); BundleContext listenerBc = createBundleContext(); ServiceInterestListener serviceInterestListener = c.createMock(ServiceInterestListener.class); ListenerHookImpl listenerHook = new ListenerHookImpl(bc, serviceInterestListener); ListenerInfo listener = c.createMock(ListenerInfo.class); EasyMock.expect(listener.getBundleContext()).andReturn(listenerBc); EasyMock.expect(listener.getFilter()).andReturn(filter).atLeastOnce(); // Main assertions serviceInterestListener.addServiceInterest(listenerHook.extendFilter(filter)); EasyMock.expectLastCall(); serviceInterestListener.removeServiceInterest(listenerHook.extendFilter(filter)); EasyMock.expectLastCall(); Collection<ListenerInfo> listeners = Collections.singletonList(listener); c.replay(); listenerHook.added(listeners); listenerHook.removed(listeners); c.verify(); }
public void testEndpointRemovalAdding() throws KeeperException, InterruptedException { IMocksControl c = EasyMock.createNiceControl(); BundleContext ctx = c.createMock(BundleContext.class); ZooKeeper zk = c.createMock(ZooKeeper.class); String path = ENDPOINT_PATH; expectCreated(zk, path); expectDeleted(zk, path); c.replay(); PublishingEndpointListener eli = new PublishingEndpointListener(zk, ctx); EndpointDescription endpoint = createEndpoint(); eli.endpointAdded(endpoint, null); eli.endpointAdded(endpoint, null); // should do nothing eli.endpointRemoved(endpoint, null); eli.endpointRemoved(endpoint, null); // should do nothing c.verify(); }
public void testClose() throws KeeperException, InterruptedException { IMocksControl c = EasyMock.createNiceControl(); BundleContext ctx = c.createMock(BundleContext.class); ZooKeeper zk = c.createMock(ZooKeeper.class); expectCreated(zk, ENDPOINT_PATH); expectDeleted(zk, ENDPOINT_PATH); c.replay(); PublishingEndpointListener eli = new PublishingEndpointListener(zk, ctx); EndpointDescription endpoint = createEndpoint(); eli.endpointAdded(endpoint, null); eli.close(); // should result in zk.delete(...) c.verify(); }
@SuppressWarnings("unchecked") public void testScope() { IMocksControl c = EasyMock.createNiceControl(); BundleContext ctx = c.createMock(BundleContext.class); ZooKeeper zk = c.createMock(ZooKeeper.class); @SuppressWarnings("rawtypes") ServiceRegistration sreg = c.createMock(ServiceRegistration.class); PublishingEndpointListenerFactory eplf = new PublishingEndpointListenerFactory(zk, ctx); EasyMock.expect(ctx.registerService(EasyMock.eq(EndpointListener.class.getName()), EasyMock.eq(eplf), (Dictionary<String, String>)EasyMock.anyObject())).andReturn(sreg).once(); EasyMock.expect(ctx.getProperty(EasyMock.eq("org.osgi.framework.uuid"))).andReturn("myUUID").anyTimes(); c.replay(); eplf.start(); c.verify(); }
public void testInterfaceMonitor() throws KeeperException, InterruptedException { IMocksControl c = EasyMock.createControl(); ZooKeeper zk = c.createMock(ZooKeeper.class); expect(zk.getState()).andReturn(ZooKeeper.States.CONNECTED).anyTimes(); String scope = "(myProp=test)"; String interf = "es.schaaf.test"; String node = Utils.getZooKeeperPath(interf); EndpointListener endpointListener = c.createMock(EndpointListener.class); InterfaceMonitor im = new InterfaceMonitor(zk, interf, endpointListener, scope); zk.exists(eq(node), eq(im), eq(im), EasyMock.anyObject()); EasyMock.expectLastCall().once(); expect(zk.exists(eq(node), eq(false))).andReturn(new Stat()).anyTimes(); expect(zk.getChildren(eq(node), eq(false))).andReturn(Collections.<String> emptyList()).once(); expect(zk.getChildren(eq(node), eq(im))).andReturn(Collections.<String> emptyList()).once(); c.replay(); im.start(); // simulate a zk callback WatchedEvent we = new WatchedEvent(EventType.NodeCreated, KeeperState.SyncConnected, node); im.process(we); c.verify(); }
public void testUpdateConfig() throws Exception { final File tempDir = new File("target"); IMocksControl control = EasyMock.createControl(); BundleContext bc = control.createMock(BundleContext.class); expect(bc.getDataFile("")).andReturn(tempDir); final MyZooKeeperServerMain mockServer = control.createMock(MyZooKeeperServerMain.class); control.replay(); ZookeeperStarter starter = new ZookeeperStarter(bc) { @Override protected void startFromConfig(QuorumPeerConfig config) { assertEquals(1234, config.getClientPortAddress().getPort()); assertTrue(config.getDataDir().contains(tempDir + File.separator + "zkdata")); assertEquals(2000, config.getTickTime()); assertEquals(10, config.getInitLimit()); assertEquals(5, config.getSyncLimit()); this.main = mockServer; } }; Dictionary<String, Object> props = new Hashtable<String, Object>(); props.put("clientPort", "1234"); starter.updated(props); assertNotNull(starter.main); control.verify(); }
@Test public void testDefaults() throws ConfigurationException { IMocksControl c = EasyMock.createControl(); BundleContext bctx = c.createMock(BundleContext.class); ZooKeeperDiscovery zkd = new ZooKeeperDiscovery(bctx) { @Override protected ZooKeeper createZooKeeper(String host, String port, int timeout) { Assert.assertEquals("localhost", host); Assert.assertEquals("2181", port); Assert.assertEquals(3000, timeout); return null; } }; Dictionary<String, Object> configuration = new Hashtable<String, Object>(); zkd.updated(configuration); }
@Test public void testConfig() throws ConfigurationException { IMocksControl c = EasyMock.createControl(); BundleContext bctx = c.createMock(BundleContext.class); ZooKeeperDiscovery zkd = new ZooKeeperDiscovery(bctx) { @Override protected ZooKeeper createZooKeeper(String host, String port, int timeout) { Assert.assertEquals("myhost", host); Assert.assertEquals("1", port); Assert.assertEquals(1000, timeout); return null; } }; Dictionary<String, Object> configuration = new Hashtable<String, Object>(); configuration.put("zookeeper.host", "myhost"); configuration.put("zookeeper.port", "1"); configuration.put("zookeeper.timeout", "1000"); zkd.updated(configuration); }
@SuppressWarnings({ "rawtypes" }) public void testGetService() throws ClassNotFoundException { final Object myTestProxyObject = new Object(); IMocksControl control = EasyMock.createControl(); EndpointDescription endpoint = createTestEndpointDesc(); ImportRegistrationImpl iri = new ImportRegistrationImpl(endpoint, null); BundleContext consumerContext = control.createMock(BundleContext.class); Bundle consumerBundle = control.createMock(Bundle.class); BundleWiring bundleWiring = control.createMock(BundleWiring.class); EasyMock.expect(bundleWiring.getClassLoader()).andReturn(this.getClass().getClassLoader()); EasyMock.expect(consumerBundle.adapt(BundleWiring.class)).andReturn(bundleWiring); EasyMock.expect(consumerBundle.getBundleContext()).andReturn(consumerContext); ServiceRegistration sreg = control.createMock(ServiceRegistration.class); DistributionProvider handler = mockDistributionProvider(myTestProxyObject); control.replay(); ClientServiceFactory csf = new ClientServiceFactory(endpoint, handler, iri); assertSame(myTestProxyObject, csf.getService(consumerBundle, sreg)); }
@SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void testStartStop() throws Exception { IMocksControl c = EasyMock.createControl(); BundleContext context = c.createMock(BundleContext.class); ServiceRegistration sreg = c.createMock(ServiceRegistration.class); expect(context.registerService(EasyMock.eq(DistributionProvider.class), EasyMock.anyObject(DistributionProvider.class), EasyMock.anyObject(Dictionary.class))).andReturn(sreg ); c.replay(); Activator activator = new Activator(); activator.start(context); activator.stop(context); c.verify(); }
private static <T> T doCreateMock(Class<T> type, ConstructorArgs constructorArgs, final IMocksControl control, Method... methods) { T mock; MocksControl mocksControl = ((MocksControl) control); if (constructorArgs == null) { if (methods == null) { mock = mocksControl.createMock(type); } else { mock = mocksControl.createMock(type, methods); } } else { if (methods == null) { mock = mocksControl.createMock(type, constructorArgs); } else { mock = mocksControl.createMock(type, constructorArgs, methods); } } return mock; }
public void testNoSuchEditor() throws Exception { try { ProjectContext context = new NoopProjectContext(); IMocksControl control = EasyMock.createControl(); RepositoryExpression mockRepoEx = control.createMock(RepositoryExpression.class); expect(mockRepoEx.createCodebase(context)).andReturn(null); // Codebase unneeded Expression ex = new EditExpression( mockRepoEx, new Operation(Operator.EDIT, new Term("noSuchEditor", EMPTY_MAP))); control.replay(); ex.createCodebase(context); fail(); } catch (CodebaseCreationError expected) { assertEquals("no editor noSuchEditor", expected.getMessage()); } }
@Test public void testSimple() throws Exception { IMocksControl testControl = createControl(); TestFilterChain testFilterChain = new TestFilterChain(); HttpServletRequest req = testControl.createMock(HttpServletRequest.class); HttpServletResponse res = testControl.createMock(HttpServletResponse.class); expect(req.getMethod()).andReturn("GET").anyTimes(); expect(req.getRequestURI()).andReturn("/bar/foo").anyTimes(); expect(req.getServletPath()).andReturn("/bar/foo").anyTimes(); expect(req.getContextPath()).andReturn("").anyTimes(); testControl.replay(); daggerFilter.doFilter(req, res, testFilterChain); assertFalse(testFilterChain.isTriggered()); assertFalse(fooServlet.isTriggered()); assertTrue(barServlet.isTriggered()); testControl.verify(); }
public void testSimple() throws Exception { IMocksControl testControl = createControl(); TestFilterChain testFilterChain = new TestFilterChain(); HttpServletRequest req = testControl.createMock(HttpServletRequest.class); HttpServletResponse res = testControl.createMock(HttpServletResponse.class); expect(req.getMethod()).andReturn("GET").anyTimes(); expect(req.getRequestURI()).andReturn("/bar/foo").anyTimes(); expect(req.getServletPath()).andReturn("/bar/foo").anyTimes(); expect(req.getContextPath()).andReturn("").anyTimes(); testControl.replay(); guiceFilter.doFilter(req, res, testFilterChain); assertFalse(testFilterChain.isTriggered()); assertFalse(fooServlet.isTriggered()); assertTrue(barServlet.isTriggered()); testControl.verify(); }
@Test public void testGet() throws Exception { IMocksControl control = createControl(); Response resp = control.createMock(Response.class); expect(resp.getStatus()).andReturn(200).times(3); Capture<Class<CloudantToDo>> classCapture = new Capture<Class<CloudantToDo>>(); expect(resp.readEntity(capture(classCapture))).andReturn(ctd1); replay(resp); WebTarget wt = createMockWebTarget(); Invocation.Builder builder = createBuilder(); expect(builder.get()).andReturn(resp).times(3); replay(builder); expect(wt.path(eq("bluemix-todo"))).andReturn(wt).times(2); expect(wt.path(eq("todos"))).andReturn(wt); expect(wt.path(eq("_design"))).andReturn(wt).times(1); expect(wt.path(eq("123"))).andReturn(wt); expect(wt.request(eq("application/json"))).andReturn(builder).anyTimes(); replay(wt); CloudantStore store = new CloudantStore(wt); assertEquals(ctd1.getToDo(), store.get("123")); assertEquals(CloudantToDo.class, classCapture.getValue()); verify(resp); verify(wt); verify(builder); }
@Test public void testCount() throws Exception { IMocksControl control = createControl(); Response resp = control.createMock(Response.class); expect(resp.getStatus()).andReturn(200).times(3); Capture<Class<CloudantCount>> classCapture = new Capture<Class<CloudantCount>>(); expect(resp.readEntity(capture(classCapture))).andReturn(count); replay(resp); WebTarget wt = createMockWebTarget(); Invocation.Builder builder = createBuilder(); expect(builder.get()).andReturn(resp).times(3); replay(builder); expect(wt.path(eq("bluemix-todo"))).andReturn(wt).times(2); expect(wt.path(eq("todos"))).andReturn(wt).times(2); expect(wt.path(eq("_design"))).andReturn(wt).times(2); expect(wt.path(eq("_view"))).andReturn(wt); expect(wt.path(eq("allTodos"))).andReturn(wt); expect(wt.request(eq("application/json"))).andReturn(builder).anyTimes(); replay(wt); CloudantStore store = new CloudantStore(wt); assertEquals(123, store.count()); assertEquals(CloudantCount.class, classCapture.getValue()); verify(resp); verify(wt); verify(builder); }
@Test public void testMockFinal() { IMocksControl control = EasyMock.createStrictControl(); try { control.createMock(TestClass.FinalClass.class); Assert.fail("FinalClass wasn't actually final or EasyMock has changed to support this case"); } catch(IllegalArgumentException e) { } JUnitCore core = new JUnitCore(); Result result = core.run(Request.method(TestClass.class, "testMockingFinal")); if (!result.wasSuccessful()) { if (result.getFailures().get(0).getException().getCause() instanceof MultipleFailureException) { Assert.fail(((MultipleFailureException)result.getFailures().get(0).getException().getCause()).getFailures().toString()); } else { Assert.fail(result.getFailures().toString()); } } }
@Test public void testMockParentFinalMethod() { IMocksControl control = EasyMock.createStrictControl(); try { control.createMock(TestClass.FinalChild.class); Assert.fail("FinalClass wasn't actually final or EasyMock has changed to support this case"); } catch(IllegalArgumentException e) { } JUnitCore core = new JUnitCore(); Result result = core.run(Request.method(TestClass.class, "testMockingParentFinal")); if (!result.wasSuccessful()) { if (result.getFailures().get(0).getException().getCause() instanceof MultipleFailureException) { Assert.fail(((MultipleFailureException)result.getFailures().get(0).getException().getCause()).getFailures().toString()); } else { Assert.fail(result.getFailures().toString()); } } }
protected void setUp() throws Exception { services = new LinkedHashMap(); IMocksControl mc = createNiceControl(); cfg = mc.createMock(Configuration.class); expect(cfg.getProperties()).andReturn(new Hashtable<String, Object>()); mc.replay(); bundleContext = new MockBundleContext() { public ServiceRegistration registerService(String[] clazzes, Object service, Dictionary properties) { services.put(service, properties); return super.registerService(clazzes, service, properties); } public Object getService(ServiceReference reference) { String[] clazzes = (String[]) reference.getProperty(Constants.OBJECTCLASS); if (clazzes[0].equals(ConfigurationAdmin.class.getName())) { return new MockConfigurationAdmin() { public Configuration getConfiguration(String pid) throws IOException { return cfg; } }; } else return super.getService(reference); } }; pid = "Peter Pan"; cam = new ConfigurationAdminManager(pid, bundleContext); }
@Test public void testUnwatchOnException() throws Exception { IMocksControl control = createControl(); ZooKeeperClient zkClient = control.createMock(ZooKeeperClient.class); Watcher onExpirationWatcher = control.createMock(Watcher.class); expect(zkClient.registerExpirationHandler(anyObject(Command.class))) .andReturn(onExpirationWatcher); expect(zkClient.get()).andThrow(new InterruptedException()); // See interrupted() note below. expect(zkClient.unregister(onExpirationWatcher)).andReturn(true); control.replay(); Group group = new Group(zkClient, ZooDefs.Ids.OPEN_ACL_UNSAFE, "/blabla"); ServerSetImpl serverset = new ServerSetImpl(zkClient, group); try { serverset.watch(hostSet -> {}); fail("Expected MonitorException"); } catch (DynamicHostSet.MonitorException e) { // NB: The assert is not important to this test, but the call to `Thread.interrupted()` is. // That call both returns the current interrupted status as well as clearing it. The clearing // is crucial depending on the order tests are run in this class. If this test runs before // one of the tests above that uses a `ZooKeeperClient` for example, those tests will fail // executing `ZooKeeperClient.get` which internally blocks on s sync-point that takes part in // the interruption mechanism and so immediately throws `InterruptedException` based on the // un-cleared interrupted bit. assertTrue(Thread.interrupted()); } control.verify(); }
@Test public void testDoStart() throws Exception { IMocksControl c = createNiceControl(); BundleContext context = c.createMock(BundleContext.class); expect(context.getProperty(Constants.FRAMEWORK_UUID)).andReturn("myid"); context.addServiceListener(isA(TopologyManagerExport.class)); expectLastCall(); final Capture<String> filter = newCapture(); expect(context.createFilter(EasyMock.capture(filter))) .andAnswer(new IAnswer<Filter>() { public Filter answer() throws Throwable { return FrameworkUtil.createFilter(filter.getValue()); } }).times(2); ServiceReference<?> sref = c.createMock(ServiceReference.class); Bundle bundle = c.createMock(Bundle.class); expect(sref.getBundle()).andReturn(bundle).anyTimes(); expect(context.getServiceReferences((String)null, Activator.DOSGI_SERVICES)) .andReturn(new ServiceReference[]{sref}); c.replay(); Activator activator = new Activator(); activator.doStart(context, new DefaultExportPolicy()); c.verify(); c.reset(); c.replay(); activator.doStop(context); c.verify(); }
/** * This tests if the topology manager handles a service marked to be exported correctly by exporting it to * an available RemoteServiceAdmin and notifying an EndpointListener afterwards. * * @throws Exception */ @Test public void testServiceExportUnexport() throws Exception { IMocksControl c = EasyMock.createControl(); RemoteServiceAdmin rsa = c.createMock(RemoteServiceAdmin.class); final EndpointListener notifier = c.createMock(EndpointListener.class); final ServiceReference sref = createUserService(c); EndpointDescription epd = createEndpoint(); expectServiceExported(c, rsa, notifier, sref, epd); c.replay(); EndpointRepository endpointRepo = new EndpointRepository(); endpointRepo.setNotifier(notifier); Executor executor = syncExecutor(); ExportPolicy policy = new DefaultExportPolicy(); TopologyManagerExport exportManager = new TopologyManagerExport(endpointRepo, executor, policy); exportManager.add(rsa); exportManager.serviceChanged(new ServiceEvent(ServiceEvent.REGISTERED, sref)); c.verify(); c.reset(); notifier.endpointRemoved(epd, null); expectLastCall().once(); c.replay(); exportManager.serviceChanged(new ServiceEvent(ServiceEvent.UNREGISTERING, sref)); c.verify(); c.reset(); c.replay(); exportManager.serviceChanged(new ServiceEvent(ServiceEvent.MODIFIED, sref)); c.verify(); c.reset(); c.replay(); exportManager.remove(rsa); c.verify(); }
private void expectServiceExported(IMocksControl c, RemoteServiceAdmin rsa, final EndpointListener listener, final ServiceReference sref, EndpointDescription epd) { ExportRegistration exportRegistration = createExportRegistration(c, epd); EasyMock.expect(rsa.exportService(EasyMock.same(sref), (Map<String, Object>)EasyMock.anyObject())) .andReturn(Collections.singletonList(exportRegistration)).once(); listener.endpointAdded(epd, null); EasyMock.expectLastCall().once(); }
private ExportRegistration createExportRegistration(IMocksControl c, EndpointDescription endpoint) { ExportRegistration exportRegistration = c.createMock(ExportRegistration.class); ExportReference exportReference = c.createMock(ExportReference.class); EasyMock.expect(exportRegistration.getExportReference()).andReturn(exportReference).anyTimes(); EasyMock.expect(exportRegistration.getException()).andReturn(null).anyTimes(); EasyMock.expect(exportReference.getExportedEndpoint()).andReturn(endpoint).anyTimes(); return exportRegistration; }
private ServiceReference createUserService(IMocksControl c, Object exportedInterfaces) { final ServiceReference sref = c.createMock(ServiceReference.class); EasyMock.expect(sref.getProperty(EasyMock.same(RemoteConstants.SERVICE_EXPORTED_INTERFACES))) .andReturn(exportedInterfaces).anyTimes(); Bundle srefBundle = c.createMock(Bundle.class); if(!"".equals(exportedInterfaces)) { EasyMock.expect(sref.getBundle()).andReturn(srefBundle).atLeastOnce(); EasyMock.expect(srefBundle.getSymbolicName()).andReturn("serviceBundleName").atLeastOnce(); } EasyMock.expect(sref.getProperty("objectClass")).andReturn("org.My").anyTimes(); return sref; }
@Test public void testAddRemove() throws InvalidSyntaxException { EndpointDescription ep1 = createEndpoint("my"); IMocksControl c = EasyMock.createControl(); ServiceReference<?> sref = createService(c); RemoteServiceAdmin rsa = c.createMock(RemoteServiceAdmin.class); EndpointListener notifier = c.createMock(EndpointListener.class); notifier.endpointAdded(ep1, null); EasyMock.expectLastCall(); c.replay(); EndpointRepository repo = new EndpointRepository(); repo.setNotifier(notifier); List<EndpointDescription> endpoints = Arrays.asList(ep1); repo.addEndpoints(sref, rsa, endpoints); c.verify(); c.reset(); notifier.endpointRemoved(ep1, null); EasyMock.expectLastCall(); c.replay(); repo.removeRemoteServiceAdmin(rsa); c.verify(); }
private ServiceReference<?> createService(IMocksControl c) { ServiceReference<?> sref = c.createMock(ServiceReference.class); Bundle bundle = c.createMock(Bundle.class); EasyMock.expect(bundle.getSymbolicName()).andReturn("myBundle"); EasyMock.expect(sref.getBundle()).andReturn(bundle); return sref; }
@SuppressWarnings("unchecked") private ServiceReference<EndpointListener> createService(IMocksControl c, String scope, String objectClass) { ServiceReference<EndpointListener> sref = c.createMock(ServiceReference.class); final Dictionary<String, String> props = new Hashtable<>(); props.put(EndpointListener.ENDPOINT_LISTENER_SCOPE, scope); props.put(Constants.OBJECTCLASS, objectClass); String[] keys = Collections.list(props.keys()).toArray(new String[]{}); EasyMock.expect(sref.getPropertyKeys()).andReturn(keys).anyTimes(); EasyMock.expect(sref.getProperty((String)EasyMock.anyObject())).andAnswer(new IAnswer<Object>() { public Object answer() throws Throwable { return props.get(getCurrentArguments()[0]); } }).anyTimes(); return sref; }
@Test public void testException() { IMocksControl c = EasyMock.createNiceControl(); Exception e = c.createMock(Exception.class); c.replay(); ImportRegistrationImpl i = new ImportRegistrationImpl(e); assertEquals(e, i.getException()); assertNull(i.getImportedEndpointDescription()); assertNull(i.getImportedService()); assertEquals(i, i.getParent()); }
@Test public void testDefaultCtor() { IMocksControl c = EasyMock.createNiceControl(); EndpointDescription endpoint = c.createMock(EndpointDescription.class); RemoteServiceAdminCore rsac = c.createMock(RemoteServiceAdminCore.class); c.replay(); ImportRegistrationImpl i = new ImportRegistrationImpl(endpoint, rsac); assertNull(i.getException()); assertEquals(i, i.getParent()); assertEquals(endpoint, i.getImportedEndpointDescription()); }
@Test public void testCloseAll() { IMocksControl c = EasyMock.createControl(); EndpointDescription endpoint = c.createMock(EndpointDescription.class); RemoteServiceAdminCore rsac = c.createMock(RemoteServiceAdminCore.class); c.replay(); ImportRegistrationImpl i1 = new ImportRegistrationImpl(endpoint, rsac); ImportRegistrationImpl i2 = new ImportRegistrationImpl(i1); ImportRegistrationImpl i3 = new ImportRegistrationImpl(i2); assertEquals(i1, i1.getParent()); assertEquals(i1, i2.getParent()); assertEquals(i1, i3.getParent()); c.verify(); c.reset(); rsac.removeImportRegistration(EasyMock.eq(i2)); EasyMock.expectLastCall().once(); c.replay(); i2.close(); c.verify(); c.reset(); rsac.removeImportRegistration(EasyMock.eq(i1)); EasyMock.expectLastCall().once(); rsac.removeImportRegistration(EasyMock.eq(i3)); EasyMock.expectLastCall().once(); c.replay(); i3.closeAll(); c.verify(); }
@Test public void testAddingWithNullValues() throws InvalidSyntaxException { IMocksControl c = EasyMock.createControl(); DistributionProvider provider = c.createMock(DistributionProvider.class); ServiceReference<DistributionProvider> providerRef = c.createMock(ServiceReference.class); EasyMock.expect(providerRef.getProperty(RemoteConstants.REMOTE_INTENTS_SUPPORTED)).andReturn(null); EasyMock.expect(providerRef.getProperty(RemoteConstants.REMOTE_CONFIGS_SUPPORTED)).andReturn(null); BundleContext context = c.createMock(BundleContext.class); String filterSt = String.format("(objectClass=%s)", DistributionProvider.class.getName()); Filter filter = FrameworkUtil.createFilter(filterSt); EasyMock.expect(context.createFilter(filterSt)).andReturn(filter); EasyMock.expect(context.getService(providerRef)).andReturn(provider); ServiceRegistration rsaReg = c.createMock(ServiceRegistration.class); EasyMock.expect(context.registerService(EasyMock.isA(String.class), EasyMock.isA(ServiceFactory.class), EasyMock.isA(Dictionary.class))) .andReturn(rsaReg).atLeastOnce(); context.addServiceListener(EasyMock.isA(ServiceListener.class), EasyMock.isA(String.class)); EasyMock.expectLastCall(); final BundleContext apiContext = c.createMock(BundleContext.class); c.replay(); DistributionProviderTracker tracker = new DistributionProviderTracker(context) { protected BundleContext getAPIContext() { return apiContext; }; }; tracker.addingService(providerRef); c.verify(); }
@Test public void testDontExportOwnServiceProxies() throws InvalidSyntaxException { IMocksControl c = EasyMock.createControl(); Bundle b = c.createMock(Bundle.class); BundleContext bc = c.createMock(BundleContext.class); EasyMock.expect(bc.getBundle()).andReturn(b).anyTimes(); bc.addServiceListener(EasyMock.<ServiceListener>anyObject(), EasyMock.<String>anyObject()); EasyMock.expectLastCall().anyTimes(); bc.removeServiceListener(EasyMock.<ServiceListener>anyObject()); EasyMock.expectLastCall().anyTimes(); Dictionary<String, String> d = new Hashtable<String, String>(); EasyMock.expect(b.getHeaders()).andReturn(d).anyTimes(); ServiceReference sref = c.createMock(ServiceReference.class); EasyMock.expect(sref.getBundle()).andReturn(b).anyTimes(); EasyMock.expect(sref.getPropertyKeys()) .andReturn(new String[]{"objectClass", "service.exported.interfaces"}).anyTimes(); EasyMock.expect(sref.getProperty("objectClass")).andReturn(new String[] {"a.b.C"}).anyTimes(); EasyMock.expect(sref.getProperty(RemoteConstants.SERVICE_IMPORTED)).andReturn(true).anyTimes(); EasyMock.expect(sref.getProperty("service.exported.interfaces")).andReturn("*").anyTimes(); DistributionProvider provider = c.createMock(DistributionProvider.class); c.replay(); RemoteServiceAdminCore rsaCore = new RemoteServiceAdminCore(bc, bc, provider); // must return an empty List as sref if from the same bundle List<ExportRegistration> exRefs = rsaCore.exportService(sref, null); assertNotNull(exRefs); assertEquals(0, exRefs.size()); // must be empty assertEquals(rsaCore.getExportedServices().size(), 0); c.verify(); }
private ProviderMethodBinding createProviderMethodBinding(Object instance, Method method) { // Ew, but the constructor of ProviderMethod is private, and this is a // simple way to create a custom one. IMocksControl control = EasyMock.createControl(); @SuppressWarnings("unchecked") ProviderMethod<Integer> providerMethod = (ProviderMethod<Integer>) control.createMock("providerMethod", ProviderMethod.class); EasyMock.expect(providerMethod.getInstance()).andStubReturn(instance); EasyMock.expect(providerMethod.getKey()).andStubReturn(Key.get(Integer.class)); EasyMock.expect(providerMethod.getMethod()).andStubReturn(method); control.replay(); // Note: guiceUtil and methodCallUtil are used in parts of the binding class // that we don't test currently, so are set to null. When tests for // getCreationStatements() and getDependencies() are written, concrete // values (mocks?) will be required. ProviderMethodBinding result = new ProviderMethodBinding( errorManager, null, null, providerMethod, Context.forText("dummy context")); control.verify(); return result; }