public HttpClient getMockHttpClient() { HttpClient mock = Mockito.mock(HttpClient.class); HttpParams paramsMock = Mockito.mock(HttpParams.class); ClientConnectionManager connectionMock = Mockito.mock(ClientConnectionManager.class); HttpResponse hrMocked = Mockito.mock(HttpResponse.class); StatusLine slMocked = Mockito.mock(StatusLine.class); Header headerMocked = Mockito.mock(Header.class); Mockito.when(connectionMock.getSchemeRegistry()) .thenReturn(SchemeRegistryFactory.createDefault()); Mockito.when(hrMocked.getEntity()).thenReturn(heMocked); Mockito.when(mock.getParams()).thenReturn(paramsMock); Mockito.when(mock.getConnectionManager()).thenReturn(connectionMock); try { Mockito.when(mock.execute(Mockito.any(HttpUriRequest.class), Mockito.any(HttpContext.class))) .thenReturn(hrMocked); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Mockito.when(hrMocked.getStatusLine()).thenReturn(slMocked); Mockito.when(slMocked.getStatusCode()).thenReturn(200); Mockito.when(heMocked.getContentType()).thenReturn(headerMocked); Mockito.when(headerMocked.getElements()).thenReturn(new HeaderElement[0]); return mock; }
@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); }
@Test public final void shouldSaveAndSetOwnerEntity() { // given given(owner.isValid()).willReturn(true); given(savedOwner.isValid()).willReturn(true); given(ownerDD.save(owner)).willReturn(savedOwner); // when stateChangeContext.setOwner(owner); // then verify(ownerDD).save(owner); verify(stateChangeEntity, never()).setField(describer.getOwnerFieldName(), owner); verify(stateChangeEntity).setField(describer.getOwnerFieldName(), savedOwner); verify(messageService, never()) .addValidationError( Mockito.eq(stateChangeContext), Mockito.anyString(), Mockito.anyString(), Mockito.any(String[].class)); verify(messageService, never()) .addValidationError( Mockito.eq(stateChangeContext), Mockito.eq((String) null), Mockito.anyString(), Mockito.any(String[].class)); verify(stateChangeEntity, never()) .setField(describer.getStatusFieldName(), StateChangeStatus.FAILURE.getStringValue()); }
@Test public void testExecRequestPersistentStatefulConnection() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test")); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE); Mockito.when( requestExecutor.execute( Mockito.same(request), Mockito.<HttpClientConnection>any(), Mockito.<HttpClientContext>any())) .thenReturn(response); Mockito.when(reuseStrategy.keepAlive(Mockito.same(response), Mockito.<HttpClientContext>any())) .thenReturn(Boolean.TRUE); Mockito.when(userTokenHandler.getUserToken(Mockito.<HttpClientContext>any())) .thenReturn("this and that"); mainClientExec.execute(route, request, context, execAware); Mockito.verify(connManager).requestConnection(route, null); Mockito.verify(connRequest).get(0, TimeUnit.MILLISECONDS); Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context); Mockito.verify(connManager) .releaseConnection(managedConn, "this and that", 0, TimeUnit.MILLISECONDS); Mockito.verify(managedConn, Mockito.never()).close(); Assert.assertEquals("this and that", context.getUserToken()); }
@SuppressWarnings("rawtypes") @Test public void withHeaderMapper() throws Exception { Object pollingConsumer = context.getBean("withHeaderMapper"); assertTrue(pollingConsumer instanceof PollingConsumer); assertEquals(headerMapper, TestUtils.getPropertyValue(pollingConsumer, "handler.headerMapper")); MessageChannel channel = context.getBean("outboundEventChannel", MessageChannel.class); Message<?> message = MessageBuilder.withPayload("hello") .setHeader(XmppHeaders.TO, "oleg") .setHeader("foobar", "foobar") .build(); XMPPConnection connection = context.getBean("testConnection", XMPPConnection.class); doAnswer( invocation -> { Object[] args = invocation.getArguments(); org.jivesoftware.smack.packet.Message xmppMessage = (org.jivesoftware.smack.packet.Message) args[0]; assertEquals("oleg", xmppMessage.getTo()); assertEquals("foobar", JivePropertiesManager.getProperty(xmppMessage, "foobar")); return null; }) .when(connection) .sendStanza(Mockito.any(org.jivesoftware.smack.packet.Message.class)); channel.send(message); verify(connection, times(1)) .sendStanza(Mockito.any(org.jivesoftware.smack.packet.Message.class)); Mockito.reset(connection); }
@Test public void usingUnsupportedBuildAreaWithLiftDistance() throws Exception { AbstractPrintFileProcessor processor = createNewPrintFileProcessor(); Graphics2D graphics = Mockito.mock(Graphics2D.class); PrintJob printJob = createTestPrintJob(processor); Mockito.when( printJob.getPrinter().getConfiguration().getSlicingProfile().getZLiftDistanceGCode()) .thenReturn("G99 ${1 + UnknownVariable * 2} ;dependent on buildArea"); Double whenBuilAreaMMCalled = printJob.getPrintFileProcessor().getBuildAreaMM(Mockito.any(PrintJob.class)); Mockito.when(whenBuilAreaMMCalled).thenReturn(null); DataAid aid = processor.initializeJobCacheWithDataAid(printJob); try { aid.customizer.setNextStep(PrinterStep.PerformExposure); processor.printImageAndPerformPostProcessing(aid, image); Assert.fail("Must throw InappropriateDeviceException"); } catch (InappropriateDeviceException e) { Mockito.verify(printJob.getPrintFileProcessor(), Mockito.times(2)) .getBuildAreaMM(Mockito.any(PrintJob.class)); } Mockito.when( printJob.getPrinter().getConfiguration().getSlicingProfile().getZLiftDistanceGCode()) .thenReturn("G99 ${1 + buildAreaMM * 2} ;dependent on buildArea"); try { aid.customizer.setNextStep(PrinterStep.PerformExposure); processor.printImageAndPerformPostProcessing(aid, image); Mockito.verify(printJob.getPrintFileProcessor(), Mockito.times(5)) .getBuildAreaMM(Mockito.any(PrintJob.class)); } catch (InappropriateDeviceException e) { Assert.fail("Should not throw InappropriateDeviceException"); } }
@Test public void testDisposeSavepointSuccess() throws Exception { replaceStdOutAndStdErr(); try { String savepointPath = "expectedSavepointPath"; ActorGateway jobManager = mock(ActorGateway.class); Promise<Object> triggerResponse = new scala.concurrent.impl.Promise.DefaultPromise<>(); when(jobManager.ask( Mockito.eq(new JobManagerMessages.DisposeSavepoint(savepointPath)), Mockito.any(FiniteDuration.class))) .thenReturn(triggerResponse.future()); triggerResponse.success(JobManagerMessages.getDisposeSavepointSuccess()); CliFrontend frontend = new MockCliFrontend(CliFrontendTestUtils.getConfigDir(), jobManager); String[] parameters = {"-d", savepointPath}; int returnCode = frontend.savepoint(parameters); assertEquals(0, returnCode); verify(jobManager, times(1)) .ask( Mockito.eq(new JobManagerMessages.DisposeSavepoint(savepointPath)), Mockito.any(FiniteDuration.class)); String outMsg = buffer.toString(); assertTrue(outMsg.contains(savepointPath)); assertTrue(outMsg.contains("disposed")); } finally { restoreStdOutAndStdErr(); } }
@Test public void shouldCancelOrder() throws IOException { // given BitMarketCancelResponse response = new BitMarketCancelResponse( true, new BitMarketBalance(createAvailable(), createBlocked()), new BitMarketAPILimit(3, 100, 12345000L), 0, null); BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class); PowerMockito.when( bitMarketAuthenticated.cancel( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq(12345L))) .thenReturn(response); Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated); // when boolean cancelled = tradeService.cancelOrder("12345"); // then assertThat(cancelled).isTrue(); }
@Test public void testIteratorNotInSplitsCompensation() throws Exception { FileInputFormat.addInputPath(conf, new Path("unused")); InputSplit[] splits = inputformat.getSplits(conf, 0); assertEquals(1, splits.length); InputSplit split = splits[0]; IteratorSetting is = new IteratorSetting( 1, PrimitiveComparisonFilter.FILTER_PREFIX + 1, PrimitiveComparisonFilter.class); is.addOption(PrimitiveComparisonFilter.P_COMPARE_CLASS, StringCompare.class.getName()); is.addOption(PrimitiveComparisonFilter.COMPARE_OPT_CLASS, Equal.class.getName()); is.addOption( PrimitiveComparisonFilter.CONST_VAL, new String(Base64.encodeBase64(new byte[] {'0'}))); is.addOption(PrimitiveComparisonFilter.COLUMN, "cf:cq"); // Mock out the predicate handler because it's just easier AccumuloPredicateHandler predicateHandler = Mockito.mock(AccumuloPredicateHandler.class); Mockito.when( predicateHandler.getIterators( Mockito.any(JobConf.class), Mockito.any(ColumnMapper.class))) .thenReturn(Arrays.asList(is)); // Set it on our inputformat inputformat.predicateHandler = predicateHandler; inputformat.getRecordReader(split, conf, null); // The code should account for the bug and update the iterators on the split List<IteratorSetting> settingsOnSplit = ((HiveAccumuloSplit) split).getSplit().getIterators(); assertEquals(1, settingsOnSplit.size()); assertEquals(is, settingsOnSplit.get(0)); }
@Test public void readWithTimeoutInputStreamTest() throws IOException, InterruptedException { int streamDelayTooLong = 200; int streamDelayOk = 5; int timeout = 100; int cpuDelay = 10; InputStream stream = org.mockito.Mockito.mock(InputStream.class); byte[] bytes = "hello".getBytes(); byte[] bytes2 = "worlds".getBytes(); byte[] checkBytes = new byte[bytes.length]; byte[] checkBytes2 = new byte[bytes2.length]; Mockito.when(stream.available()) .thenReturn(0) .thenReturn(bytes.length) .thenReturn(bytes2.length) .thenReturn(0); Mockito.when( stream.read( Mockito.any(byte[].class), Mockito.any(Integer.class), Mockito.any(Integer.class))) .thenAnswer(new InputStreamReadDelayedAnswer(streamDelayTooLong, new byte[0])) .thenAnswer(new InputStreamReadDelayedAnswer(streamDelayTooLong, bytes)) .thenAnswer(new InputStreamReadDelayedAnswer(streamDelayOk, bytes2)); int dataRead = IOUtilities.readWithTimeout(stream, checkBytes, timeout, cpuDelay); Assert.assertEquals(0, dataRead); dataRead = IOUtilities.readWithTimeout(stream, checkBytes, timeout, cpuDelay); Assert.assertEquals(bytes.length, dataRead); Assert.assertArrayEquals(bytes, checkBytes); dataRead = IOUtilities.readWithTimeout(stream, checkBytes2, timeout, cpuDelay); Assert.assertArrayEquals(bytes2, checkBytes2); }
@Test public void testPagingAfterItemWithInvalidAfterId() throws Exception { Element rsm = new BaseElement(new QName("set", new Namespace("", "http://jabber.org/protocol/rsm"))); rsm.addElement("after").setText("this is invalid"); element.addAttribute("node", "/user/[email protected]/posts"); Mockito.when(channelManager.nodeExists(anyString())).thenReturn(true); Mockito.when(channelManager.getNodeMembership(node, jid)) .thenReturn( new NodeMembershipImpl(node, jid, Subscriptions.subscribed, Affiliations.member, null)); Mockito.when( channelManager.getUserFeedItems( Mockito.any(JID.class), Mockito.any(Date.class), Mockito.anyInt(), Mockito.any(GlobalItemID.class), Mockito.eq(false))) .thenReturn(new ClosableIteratorImpl<NodeItem>(new ArrayList<NodeItem>().iterator())); Mockito.when( channelManager.getCountUserFeedItems( Mockito.any(JID.class), Mockito.any(Date.class), Mockito.eq(false))) .thenReturn(0); userItemsGet.process(element, jid, request, rsm); Packet p = queue.poll(100, TimeUnit.MILLISECONDS); assertEquals("Error expected", "error", p.getElement().attributeValue("type")); }
@BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0) @Test public void validateRetieveItemWithLastAccessUpdateTimeDelay() throws Exception { // need to ensure we wait 100 ms int wait = 100; ((DefaultAttributesHandler) repository.getAttributesHandler()).setLastRequestedResolution(wait); Thread.sleep(wait); AttributeStorage attributeStorageSpy = Mockito.spy(repository.getAttributesHandler().getAttributeStorage()); repository.getAttributesHandler().setAttributeStorage(attributeStorageSpy); ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath); resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1"); AbstractStorageItem storageItem = localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest); MatcherAssert.assertThat(storageItem, Matchers.notNullValue()); MatcherAssert.assertThat( storageItem.getLastRequested(), Matchers.greaterThan(originalLastAccessTime)); Mockito.verify(attributeStorageSpy, Mockito.times(1)) .putAttributes(Mockito.<RepositoryItemUid>any(), Mockito.<Attributes>any()); Mockito.verify(attributeStorageSpy, Mockito.times(1)) .getAttributes(Mockito.<RepositoryItemUid>any()); }
@BenchmarkOptions(benchmarkRounds = 10, warmupRounds = 1) @Test public void validateRetieveItemWithOutLastAccessUpdateTimeDelay() throws LocalStorageException, ItemNotFoundException, IOException { // do the test, but make sure the _iterations_ will not get out of the "resolution" span! // Note: this test is just broken as is, what guarantees it will finish the cycles in given X // millis? // Meaning, the assertions + rounds is wrong. ((DefaultAttributesHandler) repository.getAttributesHandler()) .setLastRequestedResolution(30000L); AttributeStorage attributeStorageSpy = Mockito.spy(repository.getAttributesHandler().getAttributeStorage()); repository.getAttributesHandler().setAttributeStorage(attributeStorageSpy); ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath); resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1"); AbstractStorageItem storageItem = localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest); MatcherAssert.assertThat(storageItem, Matchers.notNullValue()); MatcherAssert.assertThat( storageItem.getLastRequested(), Matchers.equalTo(originalLastAccessTime)); Mockito.verify(attributeStorageSpy, Mockito.times(0)) .putAttributes(Mockito.<RepositoryItemUid>any(), Mockito.<Attributes>any()); Mockito.verify(attributeStorageSpy, Mockito.times(1)) .getAttributes(Mockito.<RepositoryItemUid>any()); }
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; }
@Test public void testTriggerSavepointFailure() throws Exception { replaceStdOutAndStdErr(); try { JobID jobId = new JobID(); ActorGateway jobManager = mock(ActorGateway.class); Promise<Object> triggerResponse = new scala.concurrent.impl.Promise.DefaultPromise<>(); when(jobManager.ask( Mockito.eq(new JobManagerMessages.TriggerSavepoint(jobId)), Mockito.any(FiniteDuration.class))) .thenReturn(triggerResponse.future()); Exception testException = new Exception("expectedTestException"); triggerResponse.success(new JobManagerMessages.TriggerSavepointFailure(jobId, testException)); CliFrontend frontend = new MockCliFrontend(CliFrontendTestUtils.getConfigDir(), jobManager); String[] parameters = {jobId.toString()}; int returnCode = frontend.savepoint(parameters); assertTrue(returnCode != 0); verify(jobManager, times(1)) .ask( Mockito.eq(new JobManagerMessages.TriggerSavepoint(jobId)), Mockito.any(FiniteDuration.class)); assertTrue(buffer.toString().contains("expectedTestException")); } finally { restoreStdOutAndStdErr(); } }
@Test(expected = ExchangeException.class) public void shouldFailOnUnsuccessfulLimitOrder() throws IOException { // given BitMarketTradeResponse response = new BitMarketTradeResponse( false, null, new BitMarketAPILimit(3, 100, 12345000L), 502, "Invalid message hash"); BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class); PowerMockito.when( bitMarketAuthenticated.trade( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class), Mockito.eq("BTCAUD"), Mockito.eq("sell"), Mockito.eq(BigDecimal.ONE), Mockito.eq(BigDecimal.TEN))) .thenReturn(response); Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated); // when tradeService.placeLimitOrder( new LimitOrder( Order.OrderType.ASK, BigDecimal.ONE, CurrencyPair.BTC_AUD, "12345", null, BigDecimal.TEN)); // then fail( "BitMarketTradeService should throw ExchangeException when place limit order request was unsuccessful"); }
@Test public void testPassingInvalidAffiliationTypeSetsAffiliationToNone() throws Exception { IQ request = toIq( readStanzaAsString("/iq/pubsub/affiliation/affiliationChange.stanza") .replaceFirst("affiliation='member'", "affiliation='i-can-haz-all-the-items'")); NodeAffiliation affiliationActor = Mockito.mock(NodeAffiliation.class); Mockito.when(affiliationActor.getAffiliation()).thenReturn(Affiliations.moderator); ResultSet<NodeSubscription> subscriptions = new ResultSetImpl(new ArrayList<NodeSubscription>()); Mockito.when(channelManager.getNodeSubscriptionListeners(Mockito.anyString())) .thenReturn(subscriptions); Mockito.when(channelManager.nodeExists(node)).thenReturn(true); Mockito.when(channelManager.getUserAffiliation(Mockito.anyString(), Mockito.any(JID.class))) .thenReturn(affiliationActor); event.setChannelManager(channelManager); event.process(element, jid, request, null); Mockito.verify(channelManager) .setUserAffiliation( Mockito.anyString(), Mockito.any(JID.class), Mockito.eq(Affiliations.none)); }
@Test public void shouldGetOpenOrders() throws IOException { // given final LimitOrder[] expectedOrders = expectedOrders(); BitMarketOrdersResponse response = new BitMarketOrdersResponse( true, createOpenOrdersData(), new BitMarketAPILimit(3, 100, 12345000L), 0, null); BitMarketAuthenticated bitMarketAuthenticated = mock(BitMarketAuthenticated.class); PowerMockito.when( bitMarketAuthenticated.orders( Mockito.eq(SPECIFICATION_API_KEY), Mockito.any(ParamsDigest.class), Mockito.any(SynchronizedValueFactory.class))) .thenReturn(response); Whitebox.setInternalState(tradeService, "bitMarketAuthenticated", bitMarketAuthenticated); // when OpenOrders orders = tradeService.getOpenOrders(); List<LimitOrder> openOrders = orders.getOpenOrders(); // then assertThat(openOrders).hasSize(2); for (int i = 0; i < openOrders.size(); i++) { BitMarketAssert.assertEquals(openOrders.get(i), expectedOrders[i]); assertThat(orders.toString()).contains(expectedOrders[i].toString()); } }
/** * Make sure we can kill the job init task on job finished event for the job. * * @throws GenieException on error */ @Test public void canStopJobTask() throws GenieException { final String jobId = UUID.randomUUID().toString(); final ScheduledFuture task = Mockito.mock(ScheduledFuture.class); final JobFinishedEvent jobFinishedEvent = new JobFinishedEvent(jobId, JobFinishedReason.FAILED_TO_INIT, "something", this); Mockito.when(task.isDone()).thenReturn(true).thenReturn(false).thenReturn(false); Mockito.when(task.cancel(true)).thenReturn(true).thenReturn(false); Mockito.when(scheduler.schedule(Mockito.any(), Mockito.any(Date.class))).thenReturn(task); Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0)); Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0)); coordinator.init(jobId); coordinator.schedule(jobId, null, null, null, null, 1024); Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1)); Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024)); this.coordinator.onJobFinished(jobFinishedEvent); Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0)); Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0)); coordinator.init(jobId); coordinator.schedule(jobId, null, null, null, null, 1024); Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1)); Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024)); this.coordinator.onJobFinished(jobFinishedEvent); Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0)); Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0)); coordinator.init(jobId); coordinator.schedule(jobId, null, null, null, null, 1024); Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(1)); Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(1024)); this.coordinator.onJobFinished(jobFinishedEvent); Assert.assertThat(this.coordinator.getNumActiveJobs(), Matchers.is(0)); Assert.assertThat(this.coordinator.getUsedMemory(), Matchers.is(0)); Mockito.verify(this.unableToCancel, Mockito.times(1)).increment(); }
@Test public void noNullPointerWhenWeReturnNull() throws Exception { AbstractPrintFileProcessor processor = createNewPrintFileProcessor(); PrintJob printJob = createTestPrintJob(processor); Mockito.when( printJob .getPrinter() .getConfiguration() .getSlicingProfile() .getzLiftDistanceCalculator()) .thenReturn(";"); Mockito.when(printJob.getPrintFileProcessor().getBuildAreaMM(Mockito.any(PrintJob.class))) .thenReturn(null); DataAid aid = processor.initializeJobCacheWithDataAid(printJob); try { aid.customizer.setNextStep(PrinterStep.PerformExposure); processor.printImageAndPerformPostProcessing(aid, image); Mockito.verify(printJob.getPrinter().getGCodeControl(), Mockito.times(1)) .executeGCodeWithTemplating(Mockito.any(PrintJob.class), Mockito.anyString()); } catch (IllegalArgumentException e) { Assert.assertEquals( "The result of your lift distance script needs to evaluate to an instance of java.lang.Number", e.getMessage()); } }
@Test public void testConnectionClose() throws Exception { final InputStream instream = Mockito.mock(InputStream.class); final OutputStream outstream = Mockito.mock(OutputStream.class); Mockito.when(socket.getInputStream()).thenReturn(instream); Mockito.when(socket.getOutputStream()).thenReturn(outstream); conn.bind(socket); conn.ensureOpen(); conn.getSessionOutputBuffer().write(0); Assert.assertTrue(conn.isOpen()); conn.close(); Assert.assertFalse(conn.isOpen()); Mockito.verify(outstream, Mockito.times(1)) .write(Mockito.<byte[]>any(), Mockito.anyInt(), Mockito.anyInt()); Mockito.verify(socket, Mockito.times(1)).shutdownInput(); Mockito.verify(socket, Mockito.times(1)).shutdownOutput(); Mockito.verify(socket, Mockito.times(1)).close(); conn.close(); Mockito.verify(socket, Mockito.times(1)).close(); Mockito.verify(outstream, Mockito.times(1)) .write(Mockito.<byte[]>any(), Mockito.anyInt(), Mockito.anyInt()); }
@Before public void createTestData() throws ApplicationException { scrobbleService = new ScrobbleService(); UpdateNowPlayingClient nowPlayinglient = mock(UpdateNowPlayingClient.class); when(nowPlayinglient.updateNowPlaying(Mockito.any(Scrobble.class))) .thenReturn(new WSResponse(false, 404, "Not found")); scrobbleService.setUpdateNowPlayingClient(nowPlayinglient); ScrobbleClient scrobbleClient = mock(ScrobbleClient.class); when(scrobbleClient.scrobble(Mockito.any(Scrobble.class))) .thenReturn(new WSResponse("<lfm status=\"ok\"></lfm>")); scrobbleService.setScrobbleClient(scrobbleClient); PlayCountDao playCountDao = mock(PlayCountDao.class); scrobbleService.setPlayCountDao(playCountDao); MetaData metaData1 = new MetaData(); metaData1.setArtist("artist 1"); metaData1.setArtistId(artist1Id); metaData1.setAlbum("album 1"); metaData1.setAlbumId(album1Id); track1 = new Track(track1Id, "track 1", metaData1); track2 = new Track(track2Id, "track 2", metaData1); user1 = new LastFmUser(username1, sessionKey1); user2 = new LastFmUser(username2, sessionKey2); }
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)); }
@Test public void testExecRequestPersistentConnection() throws Exception { final HttpRoute route = new HttpRoute(target); final HttpClientContext context = new HttpClientContext(); final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test")); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when(managedConn.isStale()).thenReturn(Boolean.FALSE); Mockito.when( requestExecutor.execute( Mockito.same(request), Mockito.<HttpClientConnection>any(), Mockito.<HttpClientContext>any())) .thenReturn(response); Mockito.when(reuseStrategy.keepAlive(Mockito.same(response), Mockito.<HttpClientContext>any())) .thenReturn(Boolean.TRUE); Mockito.when( keepAliveStrategy.getKeepAliveDuration( Mockito.same(response), Mockito.<HttpClientContext>any())) .thenReturn(678L); final CloseableHttpResponse finalResponse = mainClientExec.execute(route, request, context, execAware); Mockito.verify(connManager).requestConnection(route, null); Mockito.verify(connRequest).get(0, TimeUnit.MILLISECONDS); Mockito.verify(requestExecutor, Mockito.times(1)).execute(request, managedConn, context); Mockito.verify(connManager).releaseConnection(managedConn, null, 678L, TimeUnit.MILLISECONDS); Mockito.verify(managedConn, Mockito.never()).close(); Assert.assertNotNull(finalResponse); Assert.assertTrue(finalResponse instanceof HttpResponseProxy); }
@Test public void testEquivalent() throws ResourceNotFoundException { Sensor newSensor = Mockito.mock(Sensor.class); Map<String, Object> props = new HashMap<>(); props.put("fuelType", "diesel"); props.put("constructionYear", 2015); props.put("engineDisplacement", 1234); props.put("model", "Dito"); props.put("manufacturer", "Vito"); Mockito.when(newSensor.getProperties()).thenReturn(props); SensorDao dao = createDao(); CarSimilarityServiceImpl service = new CarSimilarityServiceImpl(dao); CarSimilarityServiceImpl serviceMock = Mockito.spy(service); serviceMock.setSimilarityDefinition("/car-similarity-test.json"); Sensor equi = serviceMock.resolveEquivalent(newSensor); Assert.assertThat(equi, Matchers.is(oldSensor)); props.put("manufacturer", "vito mobile "); Sensor similar = serviceMock.resolveEquivalent(newSensor); Assert.assertThat(similar, Matchers.is(oldSensor)); Mockito.verify(serviceMock, Mockito.times(1)) .isManufacturerSimilar(Mockito.any(String.class), Mockito.any(String.class)); }
@Test public void testFailoverGood() throws Exception { AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class); AbstractClientConnectionFactory factory2 = mock(AbstractClientConnectionFactory.class); List<AbstractClientConnectionFactory> factories = new ArrayList<AbstractClientConnectionFactory>(); factories.add(factory1); factories.add(factory2); TcpConnectionSupport conn1 = makeMockConnection(); TcpConnectionSupport conn2 = makeMockConnection(); when(factory1.getConnection()).thenReturn(conn1); when(factory2.getConnection()).thenReturn(conn2); when(factory1.isActive()).thenReturn(true); when(factory2.isActive()).thenReturn(true); doThrow(new IOException("fail")).when(conn1).send(Mockito.any(Message.class)); doAnswer( new Answer<Object>() { public Object answer(InvocationOnMock invocation) throws Throwable { return null; } }) .when(conn2) .send(Mockito.any(Message.class)); FailoverClientConnectionFactory failoverFactory = new FailoverClientConnectionFactory(factories); failoverFactory.start(); GenericMessage<String> message = new GenericMessage<String>("foo"); failoverFactory.getConnection().send(message); Mockito.verify(conn2).send(message); }
@Test public void canChangeWalletNameAndPasswordIfWalletIsAlreadyOpen() { // Arrange: final WalletNamePasswordPair pair2 = createPair("n2", "p2"); final WalletDescriptor descriptor2 = createDescriptor("n2"); final TestContext context = new TestContext(); Mockito.when(context.descriptorFactory.createNew(pair2, FILE_EXTENSION)) .thenReturn(descriptor2); // Act: context.walletServices.open(context.pair); context.walletServices.move(context.pair, pair2); // Assert: // - the original is opened and the target is created Mockito.verify(context.descriptorFactory, Mockito.times(2)) .openExisting(context.pair, FILE_EXTENSION); Mockito.verify(context.descriptorFactory, Mockito.times(1)).createNew(pair2, FILE_EXTENSION); // - the original is loaded Mockito.verify(context.repository, Mockito.times(2)).load(context.descriptor); // - the target is saved final Wallet updatedWallet = context.walletServices.get(new WalletName("n2")); Assert.assertThat(updatedWallet.getName(), IsEqual.equalTo(new WalletName("n2"))); // TODO BR: Fix this // Mockito.verify(context.repository, Mockito.times(1)).save(descriptor2, updatedWallet); Mockito.verify(context.repository, Mockito.times(1)).save(Mockito.any(), Mockito.any()); // - the original wallet is deleted Mockito.verify(context.descriptor, Mockito.times(1)).delete(); }
@Test(expected = HttpException.class) public void testEstablishRouteViaProxyTunnelFailure() throws Exception { final AuthState authState = new AuthState(); final HttpRoute route = new HttpRoute(target, null, proxy, true); final HttpClientContext context = new HttpClientContext(); final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test")); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 500, "Boom"); response.setEntity(new StringEntity("Ka-boom")); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when( requestExecutor.execute( Mockito.<HttpRequest>any(), Mockito.<HttpClientConnection>any(), Mockito.<HttpClientContext>any())) .thenReturn(response); try { mainClientExec.establishRoute(authState, managedConn, route, request, context); } catch (final TunnelRefusedException ex) { final HttpResponse r = ex.getResponse(); Assert.assertEquals("Ka-boom", EntityUtils.toString(r.getEntity())); Mockito.verify(managedConn).close(); throw ex; } }
@Test public void testCategoryRemovedEventListenersCalled() { CategoryRemovedEventListener categoryRemovedEventListenerMock1 = Mockito.mock(CategoryRemovedEventListener.class); CategoryRemovedEventListener categoryRemovedEventListenerMock2 = Mockito.mock(CategoryRemovedEventListener.class); pinBoard.addCategoryRemovedEventListener(categoryRemovedEventListenerMock1); pinBoard.addCategoryRemovedEventListener(categoryRemovedEventListenerMock2); Category cat1 = new Category("cat1", false, NoteColor.DEFAULT_COLOR); Category cat2 = new Category("cat2", false, NoteColor.DEFAULT_COLOR); Category cat3 = new Category("cat3", false, NoteColor.DEFAULT_COLOR); pinBoard.addCategory(cat1); pinBoard.addCategory(cat2); pinBoard.addCategory(cat3); pinBoard.removeCategory(cat1); pinBoard.removeCategory(cat2); pinBoard.removeCategory(cat3); Mockito.verify(categoryRemovedEventListenerMock1, Mockito.times(3)) .categoryRemoved(Mockito.any(CategoryRemovedEvent.class)); Mockito.verify(categoryRemovedEventListenerMock2, Mockito.times(3)) .categoryRemoved(Mockito.any(CategoryRemovedEvent.class)); }
@Test public void testEstablishRouteViaProxyTunnel() throws Exception { final AuthState authState = new AuthState(); final HttpRoute route = new HttpRoute(target, null, proxy, true); final HttpClientContext context = new HttpClientContext(); final RequestConfig config = RequestConfig.custom().setConnectTimeout(321).build(); context.setRequestConfig(config); final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test")); final HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when( requestExecutor.execute( Mockito.<HttpRequest>any(), Mockito.<HttpClientConnection>any(), Mockito.<HttpClientContext>any())) .thenReturn(response); mainClientExec.establishRoute(authState, managedConn, route, request, context); Mockito.verify(connManager).connect(managedConn, route, 321, context); Mockito.verify(connManager).routeComplete(managedConn, route, context); final ArgumentCaptor<HttpRequest> reqCaptor = ArgumentCaptor.forClass(HttpRequest.class); Mockito.verify(requestExecutor) .execute(reqCaptor.capture(), Mockito.same(managedConn), Mockito.same(context)); final HttpRequest connect = reqCaptor.getValue(); Assert.assertNotNull(connect); Assert.assertEquals("CONNECT", connect.getRequestLine().getMethod()); Assert.assertEquals(HttpVersion.HTTP_1_1, connect.getRequestLine().getProtocolVersion()); Assert.assertEquals("foo:80", connect.getRequestLine().getUri()); }