private static MutableJobCatalog createMockCatalog(final Map<URI, JobSpec> jobSpecs) { MutableJobCatalog jobCatalog = Mockito.mock(MutableJobCatalog.class); Mockito.doAnswer( new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { JobSpec jobSpec = (JobSpec) invocation.getArguments()[0]; jobSpecs.put(jobSpec.getUri(), jobSpec); return null; } }) .when(jobCatalog) .put(Mockito.any(JobSpec.class)); Mockito.doAnswer( new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { URI uri = (URI) invocation.getArguments()[0]; jobSpecs.remove(uri); return null; } }) .when(jobCatalog) .remove(Mockito.any(URI.class)); return jobCatalog; }
private EnhancedIdentityService mockIdentityService() throws ObjectNotFoundException, OperationNotPermittedException, OrganizationRemovedException { EnhancedIdentityService idSvc = Mockito.mock(EnhancedIdentityService.class); Answer<VOUserDetails> answerGetCurrentUserDetails = new Answer<VOUserDetails>() { @Override public VOUserDetails answer(InvocationOnMock invocation) throws Throwable { for (String key : requestContext.keySet()) { stackRequestContext.put(key, requestContext.get(key)); } return authenticate(requestContext); } }; Answer<VOUser> answerGetUser = new Answer<VOUser>() { @Override public VOUser answer(InvocationOnMock invocation) throws Throwable { Object[] arguments = invocation.getArguments(); VOUser userParameter = (VOUser) arguments[0]; authenticate(requestContext); return get(userParameter); } }; Mockito.doAnswer(answerGetCurrentUserDetails).when(idSvc).getCurrentUserDetails(); Mockito.doAnswer(answerGetUser).when(idSvc).getUser(Matchers.any(VOUser.class)); Mockito.when((idSvc).getRequestContext()).thenReturn(requestContext); return idSvc; }
@Before public void setUp() { initMocks(this); map.clear(); when(mockServletContextEvent.getServletContext()).thenReturn(mockServletContext); when(mockServletContext.getAttribute(Mockito.anyString())) .then( new Answer<Object>() { public Object answer(final InvocationOnMock invocation) throws Throwable { return map.get((String) invocation.getArguments()[0]); } }); Mockito.doAnswer( new Answer<Object>() { public Object answer(final InvocationOnMock invocation) throws Throwable { final String key = (String) invocation.getArguments()[0]; final Object value = invocation.getArguments()[1]; return map.put(key, value); } }) .when(mockServletContext) .setAttribute(Mockito.anyString(), Mockito.anyObject()); Mockito.doAnswer( new Answer<Object>() { public Object answer(final InvocationOnMock invocation) throws Throwable { final Object value = invocation.getArguments()[0]; return map.remove(value); } }) .when(mockServletContext) .removeAttribute(Mockito.anyString()); victim = new WroServletContextListener(); }
private void overrideMockedBehaviour() { Mockito.doAnswer( new Answer<Object>() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final NormalizedNode<?, ?> node = (NormalizedNode<?, ?>) args[2]; if (node.getIdentifier().getNodeType().equals(Ipv4Route.QNAME) || node.getNodeType().equals(IPv4RIBSupport.PREFIX_QNAME)) { PeerTest.this.routes.put((YangInstanceIdentifier) args[1], node); } return args[1]; } }) .when(getTransaction()) .put( Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.any(YangInstanceIdentifier.class), Mockito.any(NormalizedNode.class)); Mockito.doAnswer( new Answer<Object>() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); PeerTest.this.routes.remove(args[1]); return args[1]; } }) .when(getTransaction()) .delete( Mockito.eq(LogicalDatastoreType.OPERATIONAL), Mockito.any(YangInstanceIdentifier.class)); }
public void testDoFilterNotAuthenticated() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)) .thenReturn(DummyAuthenticationHandler.class.getName()); Mockito.when(config.getInitParameterNames()) .thenReturn(new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE)).elements()); filter.init(config); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); FilterChain chain = Mockito.mock(FilterChain.class); Mockito.doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { fail(); return null; } }) .when(chain) .doFilter(Mockito.<ServletRequest>anyObject(), Mockito.<ServletResponse>anyObject()); filter.doFilter(request, response, chain); Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED); } finally { filter.destroy(); } }
@Override @BeforeMethod(groups = "fast") public void setUp() throws Exception { super.setUp(); final OSGIKillbillDataSource osgiKillbillDataSource = Mockito.mock(OSGIKillbillDataSource.class); final DataSource dataSource = Mockito.mock(DataSource.class); Mockito.when(osgiKillbillDataSource.getDataSource()).thenReturn(dataSource); final OSGIKillbillLogService osgiKillbillLogService = Mockito.mock(OSGIKillbillLogService.class); Mockito.doAnswer( new Answer() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { logger.info(Arrays.toString(invocation.getArguments())); return null; } }) .when(osgiKillbillLogService) .log(Mockito.anyInt(), Mockito.anyString()); invoiceFactory = new BusinessInvoiceFactory( BusinessExecutor.newCachedThreadPool(osgiConfigPropertiesService)); }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); Mockito.stub(mPhotoListManager.getPhotoListFetched()).toReturn(true); activityController = Robolectric.buildActivity(PhotosListViewActivity.class); subject = activityController.get(); Mockito.doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { subject.requestPermissionCallback.Granted(1); return null; } }) .when(mRequestPermissionUtils) .requestPermission( subject, Manifest.permission.ACCESS_FINE_LOCATION, subject.requestPermissionCallback, Constants.MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); flickrPhotoList = new ArrayList<FlickrPhoto>( Arrays.asList(new FlickrPhoto("some-photo", "some-small-url", "some-big-url"))); subject.setFlickrPhotoList(flickrPhotoList); activityController.create().start(); }
@Test public void requestLocation_Success() throws SecurityException { final Location expectedLocation = buildFakeLocation(provider); // set provider enabled setIsProviderEnabled(provider, true); // answer Mockito.doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final Object[] args = invocation.getArguments(); final LocationListener l = (LocationListener) args[1]; l.onLocationChanged(expectedLocation); return null; } }) .when(locationManager) .requestSingleUpdate( Mockito.eq(provider), Mockito.any(LocationListener.class), Mockito.any(Looper.class)); final RxLocationManager rxLocationManager = getDefaullRxLocationManager(); final TestSubscriber<Location> subscriber = new TestSubscriber<>(); rxLocationManager.requestLocation(provider).subscribe(subscriber); subscriber.awaitTerminalEvent(); subscriber.assertCompleted(); subscriber.assertValue(expectedLocation); }
@Before public void setUp() { Mockito.doAnswer( new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Throwable { String msg = (String) invocation.getArguments()[0]; AsyncCallback<String> callback = (AsyncCallback<String>) invocation.getArguments()[1]; callback.onSuccess("Client said: \"" + msg + "\"<br>Server answered: \"Hi!\""); return null; } }) .when(sampleApplicationService) .getMessage(any(String.class), (AsyncCallback<String>) any()); Mockito.when(button.addClickHandler(Mockito.any(ClickHandler.class))) .thenAnswer( new Answer<Object>() { public Object answer(InvocationOnMock aInvocation) throws Throwable { clickHandler = (ClickHandler) aInvocation.getArguments()[0]; return null; } }); Mockito.when(label.getText()).thenReturn(""); Mockito.when(label.getElement()).thenReturn(element); // Mocking the click handler needs to be done BEFORE the constructor is called, so the // 'clickHandler' can be extracted from the SampleWidget. sampleWidget = new SampleWidget(); }
/** Basic test for {@link Visibility#getDescription()}. */ @Test public void getDescription() throws ComponentLookupException { LocalizationContext lc = this.mocker.getInstance(LocalizationContext.class); LocalizationManager lm = this.mocker.getInstance(LocalizationManager.class); Translation t = mock(Translation.class); Block b = mock(Block.class); BlockRenderer r = this.mocker.getInstance(BlockRenderer.class, "plain/1.0"); when(lc.getCurrentLocale()).thenReturn(Locale.US); when(lm.getTranslation("phenotips.permissions.visibility.private.description", Locale.US)) .thenReturn(t); when(t.render(Locale.US)).thenReturn(b); Mockito.doAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { WikiPrinter printer = (WikiPrinter) invocation.getArguments()[1]; printer.print("Private cases are only accessible to their owners."); return null; } }) .when(r) .render(same(b), any(WikiPrinter.class)); Assert.assertEquals( "Private cases are only accessible to their owners.", this.mocker.getComponentUnderTest().getDescription()); }
@Test public void processValidModel() throws IOException { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class, Mockito.RETURNS_DEEP_STUBS); Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); // Test also that ETag header value contains quotes Mockito.doAnswer( new Answer<Void>() { public Void answer(final InvocationOnMock invocation) throws Throwable { LOG.debug("Header: {}", Arrays.toString(invocation.getArguments())); final Object[] arguments = invocation.getArguments(); if (HttpHeader.ETAG.toString().equals(arguments[0])) { final String etagHeaderValue = (String) arguments[1]; Assert.assertTrue(etagHeaderValue.matches("\".*?\"")); } return null; } }) .when(response) .setHeader(Mockito.anyString(), Mockito.anyString()); Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class))); managerFactory.create().process(); }
@SuppressWarnings("unchecked") @Test public void createLock() { ContentManipulationLockService tested = getTested(); // no any lock exists, so new is created Mockito.when(tested.configService.get(ContentManipulationLockService.CFGFILE_NAME)) .thenReturn(null); Mockito.doAnswer(new StoreValidationgAnswer(PROVIDER_1)) .when(tested.configService) .create(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME), Mockito.anyMap()); Assert.assertTrue(tested.createLock(PROVIDER_1)); Mockito.verify(tested.configService).get(ContentManipulationLockService.CFGFILE_NAME); Mockito.verify(tested.configService) .create(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME), Mockito.anyMap()); Mockito.verifyNoMoreInteractions(tested.configService); // another lock exists so new one is added Mockito.reset(tested.configService); Mockito.when(tested.configService.get(ContentManipulationLockService.CFGFILE_NAME)) .thenReturn(createCfgFileP1P2()); Mockito.doAnswer(new StoreValidationgAnswer(PROVIDER_1, PROVIDER_2, PROVIDER_3)) .when(tested.configService) .create(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME), Mockito.anyMap()); Assert.assertTrue(tested.createLock(PROVIDER_3)); Mockito.verify(tested.configService).get(ContentManipulationLockService.CFGFILE_NAME); Mockito.verify(tested.configService) .create(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME), Mockito.anyMap()); Mockito.verifyNoMoreInteractions(tested.configService); // given lock exists so no new one is added Mockito.reset(tested.configService); Mockito.when(tested.configService.get(ContentManipulationLockService.CFGFILE_NAME)) .thenReturn(createCfgFileP1P2()); Assert.assertFalse(tested.createLock(PROVIDER_2)); Mockito.verify(tested.configService).get(ContentManipulationLockService.CFGFILE_NAME); Mockito.verifyNoMoreInteractions(tested.configService); // all lock exists so no new one is added Mockito.reset(tested.configService); Mockito.when(tested.configService.get(ContentManipulationLockService.CFGFILE_NAME)) .thenReturn(createCfgFileAll()); Assert.assertFalse(tested.createLock(PROVIDER_2)); Mockito.verify(tested.configService).get(ContentManipulationLockService.CFGFILE_NAME); Mockito.verifyNoMoreInteractions(tested.configService); }
/** * Test checkstyle for true negative. * * @throws Exception If something goes wrong */ @Test public void testCheckstyleTrueNegative() throws Exception { final AuditListener listener = Mockito.mock(AuditListener.class); final Collector collector = new ChecksTest.Collector(); Mockito.doAnswer(collector).when(listener).addError(Mockito.any(AuditEvent.class)); this.check("/Valid.java", listener); MatcherAssert.assertThat(collector.summary(), Matchers.equalTo("")); Mockito.verify(listener, Mockito.times(0)).addError(Mockito.any(AuditEvent.class)); }
@Test @Named("if waiting for response") @Order(1) public void _ifWaitingForResponse() throws Exception { boolean _isBusy = this.subject.isBusy(); boolean _doubleArrow = Should.<Boolean>operator_doubleArrow(Boolean.valueOf(_isBusy), false); Assert.assertTrue( "\nExpected subject.busy => false but" + "\n subject.busy is " + new org.hamcrest.StringDescription().appendValue(Boolean.valueOf(_isBusy)).toString() + "\n subject is " + new org.hamcrest.StringDescription().appendValue(this.subject).toString() + "\n", _doubleArrow); final Answer<Callback<Response>> _function = new Answer<Callback<Response>>() { public Callback<Response> answer(final InvocationOnMock it) throws Throwable { Object[] _arguments = it.getArguments(); Object _get = _arguments[1]; return ConnectorBusySpec.this.callback = ((Callback) _get); } }; Stubber _doAnswer = Mockito.doAnswer(_function); Connection _when = _doAnswer.<Connection>when(this.connection); Command _any = Matchers.<Command>any(); Callback _any_1 = Matchers.<Callback>any(); _when.<Response>sendRequest(_any, _any_1); this.subject.<Response>execute(this.anyCommand, this.callback); boolean _isBusy_1 = this.subject.isBusy(); boolean _doubleArrow_1 = Should.<Boolean>operator_doubleArrow(Boolean.valueOf(_isBusy_1), true); Assert.assertTrue( "\nExpected subject.busy => true but" + "\n subject.busy is " + new org.hamcrest.StringDescription() .appendValue(Boolean.valueOf(_isBusy_1)) .toString() + "\n subject is " + new org.hamcrest.StringDescription().appendValue(this.subject).toString() + "\n", _doubleArrow_1); Response _response = new Response(0, ""); this.callback.handleResponse(_response); boolean _isBusy_2 = this.subject.isBusy(); Assert.assertTrue( "\nExpected subject.busy => false but" + "\n subject.busy is " + new org.hamcrest.StringDescription() .appendValue(Boolean.valueOf(_isBusy_2)) .toString() + "\n subject is " + new org.hamcrest.StringDescription().appendValue(this.subject).toString() + "\n", Should.<Boolean>operator_doubleArrow(Boolean.valueOf(_isBusy_2), false)); }
/** * Another regression test for HDFS-2742. This tests the following sequence: - DN does a block * report while file is open. This BR contains the block in RBW state. - The block report is * delayed in reaching the standby. - The file is closed. - The standby processes the OP_ADD and * OP_CLOSE operations before the RBW block report arrives. - The standby should not mark the * block as corrupt. */ @Test public void testRBWReportArrivesAfterEdits() throws Exception { final CountDownLatch brFinished = new CountDownLatch(1); DelayAnswer delayer = new GenericTestUtils.DelayAnswer(LOG) { @Override protected Object passThrough(InvocationOnMock invocation) throws Throwable { try { return super.passThrough(invocation); } finally { // inform the test that our block report went through. brFinished.countDown(); } } }; FSDataOutputStream out = fs.create(TEST_FILE_PATH); try { AppendTestUtil.write(out, 0, 10); out.hflush(); DataNode dn = cluster.getDataNodes().get(0); DatanodeProtocolClientSideTranslatorPB spy = DataNodeTestUtils.spyOnBposToNN(dn, nn2); Mockito.doAnswer(delayer) .when(spy) .blockReport( Mockito.<DatanodeRegistration>anyObject(), Mockito.anyString(), Mockito.<StorageBlockReport[]>anyObject()); dn.scheduleAllBlockReport(0); delayer.waitForCall(); } finally { IOUtils.closeStream(out); } cluster.transitionToStandby(0); cluster.transitionToActive(1); delayer.proceed(); brFinished.await(); // Verify that no replicas are marked corrupt, and that the // file is readable from the failed-over standby. BlockManagerTestUtil.updateState(nn1.getNamesystem().getBlockManager()); BlockManagerTestUtil.updateState(nn2.getNamesystem().getBlockManager()); assertEquals(0, nn1.getNamesystem().getCorruptReplicaBlocks()); assertEquals(0, nn2.getNamesystem().getCorruptReplicaBlocks()); DFSTestUtil.readFile(fs, TEST_FILE_PATH); }
@SuppressWarnings("unchecked") @Test public void createLockAll() { ContentManipulationLockService tested = getTested(); Mockito.reset(tested.configService); Mockito.doAnswer(new StoreValidationgAnswer(ContentManipulationLockService.API_ID_ALL)) .when(tested.configService) .create(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME), Mockito.anyMap()); tested.createLockAll(); Mockito.verify(tested.configService) .create(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME), Mockito.anyMap()); Mockito.verifyNoMoreInteractions(tested.configService); }
@Test public void testStats() throws InterruptedException { final CountDownLatch afterHandleLatch = new CountDownLatch(1); DefaultMessageHandlerMetrics handlerMetrics = TestUtils.getPropertyValue( this.handler, "handlerMetrics", DefaultMessageHandlerMetrics.class); handlerMetrics = Mockito.spy(handlerMetrics); Mockito.doAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object result = invocation.callRealMethod(); afterHandleLatch.countDown(); return result; } }) .when(handlerMetrics) .afterHandle(Mockito.any(MetricsContext.class), Mockito.eq(Boolean.TRUE)); new DirectFieldAccessor(this.handler).setPropertyValue("handlerMetrics", handlerMetrics); Integer active = new MessagingTemplate(this.input).convertSendAndReceive("foo", Integer.class); assertEquals(1, active.intValue()); assertTrue(afterHandleLatch.await(10, TimeUnit.SECONDS)); assertEquals(0, this.handler.getActiveCount()); assertEquals(1, this.handler.getHandleCount()); assertThat(this.handler.getDuration().getMax(), greaterThan(99.0)); assertThat(this.handler.getDuration().getMax(), lessThan(10000.0)); assertEquals(1, this.input.getSendCount()); assertEquals(1, this.input.getReceiveCount()); assertEquals(1, this.next.getSendCount()); assertThat(this.next.getSendDuration().getMax(), greaterThan(99.0)); assertThat(this.next.getSendDuration().getMax(), lessThan(10000.0)); Message<?> fromInbound = this.output.receive(10000); assertNotNull(fromInbound); assertEquals(0, fromInbound.getPayload()); fromInbound = this.output.receive(10000); assertNotNull(fromInbound); assertEquals(1, fromInbound.getPayload()); assertThat(this.source.getMessageCount(), greaterThanOrEqualTo(2)); assertThat(this.nullChannel.getSendCount(), greaterThanOrEqualTo(2)); assertThat(this.pubsub.getSendCount(), greaterThanOrEqualTo(2)); }
public void testDoFilterAuthenticated() throws Exception { AuthenticationFilter filter = new AuthenticationFilter(); try { FilterConfig config = Mockito.mock(FilterConfig.class); Mockito.when(config.getInitParameter(AuthenticationFilter.AUTH_TYPE)) .thenReturn(DummyAuthenticationHandler.class.getName()); Mockito.when(config.getInitParameterNames()) .thenReturn(new Vector(Arrays.asList(AuthenticationFilter.AUTH_TYPE)).elements()); filter.init(config); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("http://foo:8080/bar")); AuthenticationToken token = new AuthenticationToken("u", "p", "t"); token.setExpires(System.currentTimeMillis() + 1000); Signer signer = new Signer("alfredo".getBytes()); String tokenSigned = signer.sign(token.toString()); Cookie cookie = new Cookie(AuthenticatedURL.AUTH_COOKIE, tokenSigned); Mockito.when(request.getCookies()).thenReturn(new Cookie[] {cookie}); HttpServletResponse response = Mockito.mock(HttpServletResponse.class); FilterChain chain = Mockito.mock(FilterChain.class); Mockito.doAnswer( new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); HttpServletRequest request = (HttpServletRequest) args[0]; assertEquals("u", request.getRemoteUser()); assertEquals("p", request.getUserPrincipal().getName()); return null; } }) .when(chain) .doFilter(Mockito.<ServletRequest>anyObject(), Mockito.<ServletResponse>anyObject()); filter.doFilter(request, response, chain); } finally { filter.destroy(); } }
/** * Creates a {@link MediaRouter} mock that will capture the callback argument when {@link * MediaRouter#addCallback(MediaRouteSelector, Callback, int)} is called and sets it to {@link * #sCallback}. */ public static MediaRouter createCapturingMock() { MediaRouter mediaRouter = mock(MediaRouter.class); final ArgumentCaptor<Callback> callbackArg = ArgumentCaptor.forClass(Callback.class); final Answer<?> addCallbackAnswer = new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) { sCallback = callbackArg.getValue(); return null; } }; Mockito.doAnswer(addCallbackAnswer) .when(mediaRouter) .addCallback(any(MediaRouteSelector.class), callbackArg.capture(), anyInt()); return mediaRouter; }
private void setupTransaction(int isolation) throws RollbackException, SystemException { txn = Mockito.mock(Transaction.class); Mockito.doAnswer( new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { synch = (Synchronization) invocation.getArguments()[0]; return null; } }) .when(txn) .registerSynchronization((Synchronization) Mockito.anyObject()); Mockito.stub(txn.toString()).toReturn("txn"); tc = new TransactionContext(); tc.setTransaction(txn); tc.setIsolationLevel(isolation); tc.setTransactionType(Scope.REQUEST); }
@SuppressWarnings("unchecked") @Test public void removeLock() { ContentManipulationLockService tested = getTested(); // case - no any lock exists Mockito.when(tested.configService.get(ContentManipulationLockService.CFGFILE_NAME)) .thenReturn(null); Assert.assertTrue(tested.removeLock(PROVIDER_1)); Mockito.verify(tested.configService).get(ContentManipulationLockService.CFGFILE_NAME); Mockito.verifyNoMoreInteractions(tested.configService); // case - all lock exists so nothing removed Mockito.reset(tested.configService); Mockito.when(tested.configService.get(ContentManipulationLockService.CFGFILE_NAME)) .thenReturn(createCfgFileAll()); Assert.assertFalse(tested.removeLock(PROVIDER_1)); Mockito.verify(tested.configService).get(ContentManipulationLockService.CFGFILE_NAME); Mockito.verifyNoMoreInteractions(tested.configService); // case - p1 removed from two Mockito.reset(tested.configService); Mockito.when(tested.configService.get(ContentManipulationLockService.CFGFILE_NAME)) .thenReturn(createCfgFileP1P2()); Mockito.doAnswer(new StoreValidationgAnswer(PROVIDER_2)) .when(tested.configService) .create(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME), Mockito.anyMap()); Assert.assertTrue(tested.removeLock(PROVIDER_1)); Mockito.verify(tested.configService).get(ContentManipulationLockService.CFGFILE_NAME); Mockito.verify(tested.configService) .create(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME), Mockito.anyMap()); Mockito.verifyNoMoreInteractions(tested.configService); // case - last one removed Mockito.reset(tested.configService); Mockito.when(tested.configService.get(ContentManipulationLockService.CFGFILE_NAME)) .thenReturn(createCfgFile(PROVIDER_1)); Assert.assertTrue(tested.removeLock(PROVIDER_1)); Mockito.verify(tested.configService).get(ContentManipulationLockService.CFGFILE_NAME); Mockito.verify(tested.configService) .delete(Mockito.eq(ContentManipulationLockService.CFGFILE_NAME)); Mockito.verifyNoMoreInteractions(tested.configService); }
@Before public void setUp() throws Exception { DatagramSocket serverSocket = startFakeTurnServer(); instance = new TurnClientImpl(); instance.scheduledExecutorService = scheduledExecutorService; instance.lobbyServerAccessor = lobbyServerAccessor; instance.turnHost = serverSocket.getLocalAddress().getHostAddress(); instance.turnPort = serverSocket.getLocalPort(); eventsReceivedByTurnServer = new LinkedBlockingQueue<>(); Mockito.doAnswer( invocation -> { invocation.getArgumentAt(0, Runnable.class).run(); return null; }) .when(scheduledExecutorService) .execute(any()); instance.postConstruct(); }
@Test public void shouldFallbackToExternalResourceLocatorWhenDispatcherReturns404() throws Exception { victim = new DispatcherStreamLocator() { @Override UriLocator createExternalResourceLocator() { return mockUriLocator; } }; final String location = "/some/location.js"; when(mockRequest.getRequestDispatcher(location)).thenReturn(mockDispatcher); Mockito.doAnswer( new Answer<Void>() { public Void answer(final InvocationOnMock invocation) throws Throwable { // simulate the dispatched response is empty return null; } }) .when(mockDispatcher) .include(Mockito.any(HttpServletRequest.class), Mockito.any(HttpServletResponse.class)); victim.getInputStream(mockRequest, mockResponse, location); verify(mockUriLocator).locate(Mockito.anyString()); }
/** * Test checkstyle for true positive. * * @throws Exception If something goes wrong */ @Test public void testCheckstyleTruePositive() throws Exception { final AuditListener listener = Mockito.mock(AuditListener.class); final Collector collector = new ChecksTest.Collector(); Mockito.doAnswer(collector).when(listener).addError(Mockito.any(AuditEvent.class)); this.check("/Invalid.java", listener); final String[] violations = StringUtils.split( IOUtils.toString( this.getClass().getResourceAsStream(String.format("%s/violations.txt", this.dir))), "\n"); for (final String line : violations) { final String[] sectors = StringUtils.split(line, ":"); final Integer pos = Integer.valueOf(sectors[0]); final String needle = sectors[1].trim(); MatcherAssert.assertThat( collector.has(pos, needle), Matchers.describedAs( String.format( "Line no.%d ('%s') not reported by %s: '%s'", pos, needle, this.dir, collector.summary()), Matchers.is(true))); } }
@Test public void testRpcFailover() throws Exception { String appPath = testMeta.dir; Configuration conf = new Configuration(false); final AtomicBoolean timedout = new AtomicBoolean(); StreamingContainerUmbilicalProtocol impl = MockitoUtil.mockProtocol(StreamingContainerUmbilicalProtocol.class); Mockito.doAnswer( new org.mockito.stubbing.Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { LOG.debug("got call: " + invocation.getMethod()); if (!timedout.get()) { try { timedout.set(true); Thread.sleep(1000); } catch (Exception e) { } // throw new RuntimeException("fail"); } return null; } }) .when(impl) .log("containerId", "timeout"); Server server = new RPC.Builder(conf) .setProtocol(StreamingContainerUmbilicalProtocol.class) .setInstance(impl) .setBindAddress("0.0.0.0") .setPort(0) .setNumHandlers(1) .setVerbose(false) .build(); server.start(); InetSocketAddress address = NetUtils.getConnectAddress(server); LOG.info("Mock server listening at " + address); int rpcTimeoutMillis = 500; int retryDelayMillis = 100; int retryTimeoutMillis = 500; FSRecoveryHandler recoveryHandler = new FSRecoveryHandler(appPath, conf); URI uri = RecoverableRpcProxy.toConnectURI( address, rpcTimeoutMillis, retryDelayMillis, retryTimeoutMillis); recoveryHandler.writeConnectUri(uri.toString()); RecoverableRpcProxy rp = new RecoverableRpcProxy(appPath, conf); StreamingContainerUmbilicalProtocol protocolProxy = rp.getProxy(); protocolProxy.log("containerId", "msg"); // simulate socket read timeout try { protocolProxy.log("containerId", "timeout"); Assert.fail("expected socket timeout"); } catch (java.net.SocketTimeoutException e) { // expected } Assert.assertTrue("timedout", timedout.get()); rp.close(); // test success on retry timedout.set(false); retryTimeoutMillis = 1500; uri = RecoverableRpcProxy.toConnectURI( address, rpcTimeoutMillis, retryDelayMillis, retryTimeoutMillis); recoveryHandler.writeConnectUri(uri.toString()); protocolProxy.log("containerId", "timeout"); Assert.assertTrue("timedout", timedout.get()); rp.close(); server.stop(); }
public <X> X whenSpy(X spy) { return Mockito.doAnswer(this).when(spy); }
@Test public void testGetTokensForHftpFS() throws IOException, URISyntaxException { HftpFileSystem hfs = mock(HftpFileSystem.class); DelegationTokenSecretManager dtSecretManager = NameNodeAdapter.getDtSecretManager(dfsCluster.getNamesystem()); String renewer = "renewer"; jConf.set(JTConfig.JT_USER_NAME, renewer); DelegationTokenIdentifier dtId = new DelegationTokenIdentifier(new Text("user"), new Text(renewer), null); final Token<DelegationTokenIdentifier> t = new Token<DelegationTokenIdentifier>(dtId, dtSecretManager); final URI uri = new URI("hftp://host:2222/file1"); final String fs_addr = SecurityUtil.buildDTServiceName(uri, NameNode.DEFAULT_PORT); t.setService(new Text(fs_addr)); // when(hfs.getUri()).thenReturn(uri); Mockito.doAnswer( new Answer<URI>() { @Override public URI answer(InvocationOnMock invocation) throws Throwable { return uri; } }) .when(hfs) .getUri(); // when(hfs.getDelegationToken()).thenReturn((Token<? extends TokenIdentifier>) t); Mockito.doAnswer( new Answer<Token<DelegationTokenIdentifier>>() { @Override public Token<DelegationTokenIdentifier> answer(InvocationOnMock invocation) throws Throwable { return t; } }) .when(hfs) .getDelegationToken(renewer); // when(hfs.getDelegationTokens()).thenReturn((Token<? extends TokenIdentifier>) t); Mockito.doAnswer( new Answer<List<Token<DelegationTokenIdentifier>>>() { @Override public List<Token<DelegationTokenIdentifier>> answer(InvocationOnMock invocation) throws Throwable { return Collections.singletonList(t); } }) .when(hfs) .getDelegationTokens(renewer); // when(hfs.getCanonicalServiceName).thenReturn(fs_addr); Mockito.doAnswer( new Answer<String>() { @Override public String answer(InvocationOnMock invocation) throws Throwable { return fs_addr; } }) .when(hfs) .getCanonicalServiceName(); Credentials credentials = new Credentials(); Path p = new Path(uri.toString()); System.out.println("Path for hftp=" + p + "; fs_addr=" + fs_addr + "; rn=" + renewer); TokenCache.obtainTokensForNamenodesInternal(hfs, credentials, jConf); Collection<Token<? extends TokenIdentifier>> tns = credentials.getAllTokens(); assertEquals("number of tokens is not 1", 1, tns.size()); boolean found = false; for (Token<? extends TokenIdentifier> tt : tns) { System.out.println("token=" + tt); if (tt.getKind().equals(DelegationTokenIdentifier.HDFS_DELEGATION_KIND) && tt.getService().equals(new Text(fs_addr))) { found = true; assertEquals("different token", tt, t); } assertTrue("didn't find token for " + p, found); } }
@Before public void setUp() throws Exception { // Mocks ServerManagementContext smCtxt = Mockito.mock(ServerManagementContext.class, Mockito.RETURNS_MOCKS); ClientHandshakeAckMessage msg = mock(ClientHandshakeAckMessage.class); final MessageChannelInternal channel = mock(MessageChannelInternal.class); ChannelManager chMgr = mock(ChannelManager.class); ChannelStats stats = mock(ChannelStats.class); final ArgumentCaptor<ChannelID> cidCollector = ArgumentCaptor.forClass(ChannelID.class); when(channel.getChannelID()) .then( new Answer<ChannelID>() { @Override public ChannelID answer(InvocationOnMock invocation) throws Throwable { return cidCollector.getValue(); } }); final ArgumentCaptor<ChannelManagerEventListener> lsnrCaptor = ArgumentCaptor.forClass(ChannelManagerEventListener.class); Mockito.doNothing().when(chMgr).addEventListener(lsnrCaptor.capture()); when(channel.getRemoteAddress()).thenReturn(new TCSocketAddress(8192)); when(channel.createMessage(TCMessageType.CLIENT_HANDSHAKE_ACK_MESSAGE)).thenReturn(msg); when(chMgr.getChannel(cidCollector.capture())).thenReturn(channel); when(msg.getChannel()).thenReturn(channel); channelMgrMbean = new DSOChannelManagerImpl(chMgr, mock(TCConnectionManager.class), "1.0"); Mockito.doAnswer( new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { lsnrCaptor.getValue().channelRemoved(channel); return null; } }) .when(channel) .close(); when(smCtxt.getChannelManager()).thenReturn((DSOChannelManagerMBean) channelMgrMbean); when(stats.getCounter(Matchers.same(channel), Matchers.startsWith("serverMap"))) .thenReturn(mock(SampledCumulativeCounter.class)); when(stats.getCounter( Matchers.same(channel), Matchers.argThat( new ArgumentMatcher<String>() { @Override public boolean matches(Object argument) { // Ugly, ugly, ugly String str = (String) argument; return !str.startsWith("serverMap"); } }))) .thenReturn(SampledCounter.NULL_SAMPLED_COUNTER); when(smCtxt.getChannelStats()).thenReturn(stats); mbeanSvr = mock(MBeanServer.class); dso = new DSO( smCtxt, mock(ServerConfigurationContext.class), mbeanSvr, mock(TerracottaOperatorEventHistoryProvider.class)); }
@Test public void testPerform() { attachments = Arrays.asList(customer, b2BRegistrationModel); Mockito.doAnswer( new Answer<Object>() { @Override public Object answer(final InvocationOnMock invocation) { customers = new LinkedList<>(); return null; } }) .when(modelService) .remove(customer); Mockito.doAnswer( new Answer<Object>() { @Override public Object answer(final InvocationOnMock invocation) { customers = new ArrayList<CustomerModel>(); customers.add(b2BCustomer); return null; } }) .when(modelService) .save(b2BCustomer); Mockito.doAnswer( new Answer<Object>() { @Override public Object answer(final InvocationOnMock invocation) { attachments = new LinkedList<ItemModel>(); attachments = Arrays.asList(createB2BCustomerModel(customers.get(0)), b2BRegistrationModel); return null; } }) .when(workflowAttachmentService) .addItems(any(WorkflowModel.class), any(attachments.getClass())); workflowAttachmentService.addItems(workflowActionModel.getWorkflow(), attachments); when(userService.getUserForUID(b2BRegistrationModel.getEmail(), CustomerModel.class)) .thenReturn(customer); final List<ItemModel> customerAsList = new LinkedList<ItemModel>(); customerAsList.add(customer); when(workflowAttachmentService.getAttachmentsForAction( workflowActionModel, CustomerModel.class.getName())) .thenReturn(customerAsList); final List<ItemModel> b2BRegistrationModelAsList = new LinkedList<ItemModel>(); b2BRegistrationModelAsList.add(b2BRegistrationModel); when(workflowAttachmentService.getAttachmentsForAction( workflowActionModel, B2BRegistrationModel.class.getName())) .thenReturn(b2BRegistrationModelAsList); when(modelService.create(B2BCustomerModel.class)).thenReturn(b2BCustomer); final WorkflowModel workflowModel = new WorkflowModel(); workflowModel.setActions(Arrays.asList(workflowActionModel)); workflowActionModel.setWorkflow(workflowModel); final WorkflowDecisionModel decision = registrationApprovedAutomatedWorkflowTemplateJob.perform(workflowActionModel); assertEquals("The right decision shoule be returned", decision, workflowDecisionModel); assertTrue( "B2BCustomer should have been created", attachments.get(0) instanceof B2BCustomerModel); assertEquals( "B2BCustomer should have been assigned a B2BUnit", ((B2BCustomerModel) attachments.get(0)).getDefaultB2BUnit().getName(), b2bUnitModel.getName()); assertTrue( "b2BRegistrationModel should still be in workflow attachment", attachments.get(1).getClass().getName().endsWith("B2BRegistrationModel")); }
private void makeDefaultCut() { Mockito.when(shs.getNumCriticalSlots()).thenReturn(1); Mockito.when(shsUpgrade.getHeatSinkType()).thenReturn(shs); Mockito.when(dhs.getNumCriticalSlots()).thenReturn(2); Mockito.when(dhsUpgrade.getHeatSinkType()).thenReturn(dhs); Mockito.when(upgrades.getHeatSink()).thenReturn(shsUpgrade); Mockito.when(component.getItemsEquipped()).thenReturn(items); Mockito.when(component.getEngineHeatsinksMax()).thenReturn(engineHsSlots); Mockito.doAnswer( new Answer<Void>() { @Override public Void answer(InvocationOnMock aInvocation) throws Throwable { if (equippedHs >= maxEquippableNewType) throw new IllegalArgumentException("Can't Add!"); equippedHs++; return null; } }) .when(component) .addItem(newType); Mockito.when(component.canEquip(newType)) .then( new Answer<EquipResult>() { @Override public EquipResult answer(InvocationOnMock aInvocation) throws Throwable { if (equippedHs < maxEquippableNewType) { return EquipResult.SUCCESS; } return EquipResult.make(Type.NotEnoughSlots); } }); Mockito.doAnswer( new Answer<Void>() { @Override public Void answer(InvocationOnMock aInvocation) throws Throwable { if (equippedHs <= 0) throw new IllegalArgumentException("Can't remove!"); equippedHs--; return null; } }) .when(component) .removeItem(oldType); Mockito.when(component.canRemoveItem(oldType)) .then( new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock aInvocation) throws Throwable { return equippedHs > 0; } }); Mockito.when(loadout.getName()).thenReturn("Mock Loadout"); Mockito.when(loadout.getUpgrades()).thenReturn(upgrades); Mockito.when(loadout.getComponents()).thenReturn(Arrays.asList(component)); Mockito.when(loadout.canEquip(newType)) .then( new Answer<EquipResult>() { @Override public EquipResult answer(InvocationOnMock aInvocation) throws Throwable { if (equippedHs < maxGloballyEquippableNewType) { return EquipResult.SUCCESS; } return EquipResult.make(Type.NotEnoughSlots); } }); }