org.mockito.invocation.InvocationOnMock Java Examples
The following examples show how to use
org.mockito.invocation.InvocationOnMock.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InputChannelTestUtils.java From Flink-CEPplus with Apache License 2.0 | 6 votes |
/** * Creates a result partition manager that ignores all IDs, and simply returns the given * subpartitions in sequence. */ public static ResultPartitionManager createResultPartitionManager(final ResultSubpartition[] sources) throws Exception { final Answer<ResultSubpartitionView> viewCreator = new Answer<ResultSubpartitionView>() { private int num = 0; @Override public ResultSubpartitionView answer(InvocationOnMock invocation) throws Throwable { BufferAvailabilityListener channel = (BufferAvailabilityListener) invocation.getArguments()[2]; return sources[num++].createReadView(channel); } }; ResultPartitionManager manager = mock(ResultPartitionManager.class); when(manager.createSubpartitionView( any(ResultPartitionID.class), anyInt(), any(BufferAvailabilityListener.class))) .thenAnswer(viewCreator); return manager; }
Example #2
Source File: PerWorldInventoryInitializationTest.java From PerWorldInventory with GNU General Public License v3.0 | 6 votes |
@Before public void setUpPlugin() throws IOException { dataFolder = temporaryFolder.newFolder(); // Wire various Bukkit components setField(Bukkit.class, "server", null, server); given(server.getLogger()).willReturn(mock(Logger.class)); given(server.getScheduler()).willReturn(mock(BukkitScheduler.class)); given(server.getPluginManager()).willReturn(pluginManager); given(server.getVersion()).willReturn("1.9.4-RC1"); // SettingsManager always returns the default given(settings.getProperty(any(Property.class))).willAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { return ((Property<?>) invocation.getArguments()[0]).getDefaultValue(); } }); // PluginDescriptionFile is final and so cannot be mocked PluginDescriptionFile descriptionFile = new PluginDescriptionFile( "PerWorldInventory", "N/A", PerWorldInventory.class.getCanonicalName()); JavaPluginLoader pluginLoader = new JavaPluginLoader(server); plugin = new PerWorldInventory(pluginLoader, descriptionFile, dataFolder, null); setField(JavaPlugin.class, "logger", plugin, mock(PluginLogger.class)); }
Example #3
Source File: TestDefaultJMSMessageConverter.java From mt-flume with Apache License 2.0 | 6 votes |
void createBytesMessage() throws Exception { BytesMessage message = mock(BytesMessage.class); when(message.getBodyLength()).thenReturn((long)BYTES.length); when(message.readBytes(any(byte[].class))).then(new Answer<Integer>() { @Override public Integer answer(InvocationOnMock invocation) throws Throwable { byte[] buffer = (byte[])invocation.getArguments()[0]; if(buffer != null) { assertEquals(buffer.length, BYTES.length); System.arraycopy(BYTES, 0, buffer, 0, BYTES.length); } return BYTES.length; } }); this.message = message; }
Example #4
Source File: WXUtilsTest.java From ucar-weex-core with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { super.setUp(); Map<String, String> map = new HashMap<>(); map.put(WXConfig.scale, Float.toString(TEST_DENSITY)); PowerMockito.mockStatic(WXEnvironment.class); PowerMockito.when(WXEnvironment.class, "getConfig").thenReturn(map); PowerMockito.mockStatic(WXViewUtils.class); PowerMockito.when(WXViewUtils.class, "getScreenWidth").thenReturn(TEST_SCREEN_WIDTH); PowerMockito.mockStatic(WXSDKInstance.class); PowerMockito.when(WXSDKInstance.class, "getViewPortWidth").thenReturn(TEST_VIEW_PORT); PowerMockito.mockStatic(TextUtils.class); PowerMockito.when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { CharSequence a = (CharSequence) invocation.getArguments()[0]; return !(a != null && a.length() > 0); } }); // also look at @PrepareForTest if add mock of new class }
Example #5
Source File: RangerKylinAuthorizerTest.java From ranger with Apache License 2.0 | 6 votes |
/** * Help function: mock kylin projects, to match projectUuid and projectName */ private static void mockKylinProjects() { KylinConfig kylinConfig = KylinConfig.getInstanceFromEnv(); ProjectManager projectManager = mock(ProjectManager.class); @SuppressWarnings({ "rawtypes", "unchecked" }) Map<Class, Object> managersCache = (Map<Class, Object>) ReflectionTestUtils.getField(kylinConfig, "managersCache"); managersCache.put(ProjectManager.class, projectManager); Answer<ProjectInstance> answer = new Answer<ProjectInstance>() { @Override public ProjectInstance answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); if (args == null || args.length == 0) { return null; } String uuid = (String) args[0]; return uuid2Projects.get(uuid); } }; when(projectManager.getPrjByUuid(anyString())).thenAnswer(answer); }
Example #6
Source File: QueryReadValueTest.java From gdx-fireapp with Apache License 2.0 | 6 votes |
@Test public void run_ok() { // Given Database database = spy(Database.class); final DataSnapshot dataSnapshot = Mockito.mock(DataSnapshot.class); Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) { ((ValueEventListener) invocation.getArgument(0)).onDataChange(dataSnapshot); return null; } }).when(databaseReference).addListenerForSingleValueEvent(Mockito.any(ValueEventListener.class)); database.inReference("test"); QueryReadValue query = new QueryReadValue(database, "/test"); ConverterPromise promise = spy(ConverterPromise.class); promise.with(Mockito.mock(FirebaseMapConverter.class), String.class); // When query.with(promise).withArgs(String.class).execute(); // Then }
Example #7
Source File: TestWPBCmsContentService.java From cms with Apache License 2.0 | 6 votes |
@Test public void test_getContentProvider() { try { PowerMockito.doAnswer(new Answer<Void>() { public Void answer(InvocationOnMock invocation) { DefaultContentService contentService = (DefaultContentService)invocation.getMock(); WPBContentProvider mockProvider = EasyMock.createMock(WPBContentProvider.class); Whitebox.setInternalState(contentService, "contentProvider", mockProvider); return null; } }).when(contentService, "initializeContentProvider"); WPBContentProvider result = contentService.getContentProvider(); assertTrue (result != null); } catch (Exception e) { assertTrue(false); } }
Example #8
Source File: LocalStreamBuilderTest.java From streams with Apache License 2.0 | 6 votes |
/** * Creates {@link org.apache.streams.core.StreamsProcessor} that passes any StreamsDatum it gets as an * input and counts the number of items it processes. * @param counter * @return */ private StreamsProcessor createPassThroughProcessor(final AtomicInteger counter) { StreamsProcessor processor = mock(StreamsProcessor.class); when(processor.process(any(StreamsDatum.class))).thenAnswer(new Answer<List<StreamsDatum>>() { @Override public List<StreamsDatum> answer(InvocationOnMock invocationOnMock) throws Throwable { List<StreamsDatum> datum = new LinkedList<>(); if(counter != null) { counter.incrementAndGet(); } datum.add((StreamsDatum) invocationOnMock.getArguments()[0] ); return datum; } }); return processor; }
Example #9
Source File: DefaultPullConsumerHolderTest.java From hermes with Apache License 2.0 | 6 votes |
@Test public void testNack() throws InterruptedException { holder.onMessage(makeMessages(0, false, "a", 1)); final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<AckMessageCommandV5> cmd = new AtomicReference<>(); when(ackManager.writeAckToBroker(any(AckMessageCommandV5.class))).thenAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { cmd.set(invocation.getArgumentAt(0, AckMessageCommandV5.class)); latch.countDown(); return true; } }); PulledBatch<String> batch = holder.poll(1, 100); List<ConsumerMessage<String>> msgs = batch.getMessages(); assertEquals(1, msgs.size()); msgs.get(0).nack(); batch.commitSync(); assertTrue(latch.await(config.getManualCommitInterval() * 3, TimeUnit.MILLISECONDS)); assertEquals(1, cmd.get().getNackedMsgs().size()); }
Example #10
Source File: TestQueryDNS.java From nifi with Apache License 2.0 | 6 votes |
@Before public void setupTest() throws Exception { this.queryDNS = new QueryDNS(); this.queryDNSTestRunner = TestRunners.newTestRunner(queryDNS); Hashtable env = new Hashtable<String, String>(); env.put(Context.INITIAL_CONTEXT_FACTORY, FakeDNSInitialDirContextFactory.class.getName()); this.queryDNS.initializeContext(env); final DirContext mockContext = FakeDNSInitialDirContextFactory.getLatestMockContext(); // Capture JNDI's getAttibutes method containing the (String) queryValue and (String[]) queryType Mockito.when( mockContext.getAttributes(Mockito.anyString(), Mockito.any(String[].class))) .thenAnswer(new Answer() { public Object answer(InvocationOnMock invocation) throws Throwable { // Craft a false DNS response // Note the DNS response will not make use of any of the mocked // query contents (all input is discarded and replies synthetically // generated return craftResponse(invocation); } }); }
Example #11
Source File: AbstractChannelInitializerTest.java From hivemq-community-edition with Apache License 2.0 | 6 votes |
@Test public void test_no_connect_idle_handler_default() throws Exception { final IdleStateHandler[] idleStateHandler = new IdleStateHandler[1]; when(pipeline.addAfter(anyString(), anyString(), any(ChannelHandler.class))).thenAnswer( new Answer<ChannelPipeline>() { @Override public ChannelPipeline answer(final InvocationOnMock invocation) throws Throwable { if (invocation.getArguments()[1].equals(NEW_CONNECTION_IDLE_HANDLER)) { idleStateHandler[0] = (IdleStateHandler) (invocation.getArguments()[2]); } return pipeline; } }); abstractChannelInitializer.initChannel(socketChannel); assertEquals(500, idleStateHandler[0].getReaderIdleTimeInMillis()); }
Example #12
Source File: EventManagerTestSupport.java From nexus-public with Eclipse Public License 1.0 | 6 votes |
@Before public final void setUpEventManager() throws Exception { eventManagerEvents = new ArrayList<Object>(); doAnswer(new Answer<Object>() { @Override public Object answer(final InvocationOnMock invocation) throws Throwable { eventManagerEvents.add(invocation.getArguments()[0]); return null; } }).when(eventManager).post(any()); }
Example #13
Source File: TestQueryElasticsearchHttp.java From localization_nifi with Apache License 2.0 | 6 votes |
private OngoingStubbing<Call> mockReturnDocument(OngoingStubbing<Call> stub, final String document, int statusCode, String statusMessage) { return stub.thenAnswer(new Answer<Call>() { @Override public Call answer(InvocationOnMock invocationOnMock) throws Throwable { Request realRequest = (Request) invocationOnMock.getArguments()[0]; Response mockResponse = new Response.Builder() .request(realRequest) .protocol(Protocol.HTTP_1_1) .code(statusCode) .message(statusMessage) .body(ResponseBody.create(MediaType.parse("application/json"), document)) .build(); final Call call = mock(Call.class); if (exceptionToThrow != null) { when(call.execute()).thenThrow(exceptionToThrow); } else { when(call.execute()).thenReturn(mockResponse); } return call; } }); }
Example #14
Source File: TaskExecutorTest.java From incubator-nemo with Apache License 2.0 | 6 votes |
@Override public InputReader answer(final InvocationOnMock invocationOnMock) throws Throwable { final List<CompletableFuture<DataUtil.IteratorWithNumBytes>> inputFutures = new ArrayList<>(SOURCE_PARALLELISM); final int elementsPerSource = DATA_SIZE / SOURCE_PARALLELISM; for (int i = 0; i < SOURCE_PARALLELISM; i++) { inputFutures.add(CompletableFuture.completedFuture( DataUtil.IteratorWithNumBytes.of(elements.subList(i * elementsPerSource, (i + 1) * elementsPerSource) .iterator()))); } final InputReader inputReader = mock(InputReader.class); final IRVertex srcVertex = (IRVertex) invocationOnMock.getArgument(1); srcVertex.setProperty(ParallelismProperty.of(SOURCE_PARALLELISM)); when(inputReader.getSrcIrVertex()).thenReturn(srcVertex); when(inputReader.read()).thenReturn(inputFutures); when(inputReader.getProperties()).thenReturn(new ExecutionPropertyMap<>("")); return inputReader; }
Example #15
Source File: CorsFilterTest.java From zeppelin with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("rawtypes") public void invalidCorsFilterTest() throws IOException, ServletException { CorsFilter filter = new CorsFilter(); HttpServletResponse mockResponse = mock(HttpServletResponse.class); FilterChain mockedFilterChain = mock(FilterChain.class); HttpServletRequest mockRequest = mock(HttpServletRequest.class); when(mockRequest.getHeader("Origin")).thenReturn("http://evillocalhost:8080"); when(mockRequest.getMethod()).thenReturn("Empty"); when(mockRequest.getServerName()).thenReturn("evillocalhost"); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocationOnMock) throws Throwable { headers[count] = invocationOnMock.getArguments()[1].toString(); count++; return null; } }).when(mockResponse).setHeader(anyString(), anyString()); filter.doFilter(mockRequest, mockResponse, mockedFilterChain); Assert.assertTrue(headers[0].equals("")); }
Example #16
Source File: DefaultMQPullConsumerTest.java From rocketmq with Apache License 2.0 | 6 votes |
@Test public void testPullMessage_Success() throws Exception { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock mock) throws Throwable { PullMessageRequestHeader requestHeader = mock.getArgument(1); return createPullResult(requestHeader, PullStatus.FOUND, Collections.singletonList(new MessageExt())); } }).when(mQClientAPIImpl).pullMessage(anyString(), any(PullMessageRequestHeader.class), anyLong(), any(CommunicationMode.class), nullable(PullCallback.class)); MessageQueue messageQueue = new MessageQueue(topic, brokerName, 0); PullResult pullResult = pullConsumer.pull(messageQueue, "*", 1024, 3); assertThat(pullResult).isNotNull(); assertThat(pullResult.getPullStatus()).isEqualTo(PullStatus.FOUND); assertThat(pullResult.getNextBeginOffset()).isEqualTo(1024 + 1); assertThat(pullResult.getMinOffset()).isEqualTo(123); assertThat(pullResult.getMaxOffset()).isEqualTo(2048); assertThat(pullResult.getMsgFoundList()).isEqualTo(new ArrayList<>()); }
Example #17
Source File: DefaultMQPullConsumerTest.java From DDMQ with Apache License 2.0 | 6 votes |
@Test public void testPullMessage_Success() throws Exception { doAnswer(new Answer() { @Override public Object answer(InvocationOnMock mock) throws Throwable { PullMessageRequestHeader requestHeader = mock.getArgument(1); return createPullResult(requestHeader, PullStatus.FOUND, Collections.singletonList(new MessageExt())); } }).when(mQClientAPIImpl).pullMessage(anyString(), any(PullMessageRequestHeader.class), anyLong(), any(CommunicationMode.class), nullable(PullCallback.class)); MessageQueue messageQueue = new MessageQueue(topic, brokerName, 0); PullResult pullResult = pullConsumer.pull(messageQueue, "*", 1024, 3); assertThat(pullResult).isNotNull(); assertThat(pullResult.getPullStatus()).isEqualTo(PullStatus.FOUND); assertThat(pullResult.getNextBeginOffset()).isEqualTo(1024 + 1); assertThat(pullResult.getMinOffset()).isEqualTo(123); assertThat(pullResult.getMaxOffset()).isEqualTo(2048); assertThat(pullResult.getMsgFoundList()).isEqualTo(new ArrayList<Object>()); }
Example #18
Source File: PayPalUnitTest.java From braintree_android with MIT License | 6 votes |
@Test public void requestOneTimePayment_doesNotCallCancelListenerWhenSuccessful() { final BraintreeFragment fragment = mMockFragmentBuilder .successResponse(stringFromFixture("paypal_hermes_response.json")) .build(); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) { Intent intent = new Intent() .setData(Uri.parse("com.braintreepayments.api.test.braintree://onetouch/v1/success?PayerID=HERMES-SANDBOX-PAYER-ID&paymentId=HERMES-SANDBOX-PAYMENT-ID&token=EC-HERMES-SANDBOX-EC-TOKEN")); PayPal.onActivityResult(fragment, RESULT_OK, intent); return null; } }).when(fragment).startActivity(any(Intent.class)); MockStaticTokenizationClient.mockTokenizeSuccess(new PayPalAccountNonce()); PayPal.requestOneTimePayment(fragment, new PayPalRequest("1")); verify(fragment, never()).postCancelCallback(anyInt()); }
Example #19
Source File: AuthTest.java From gdx-fireapp with Apache License 2.0 | 6 votes |
@Test public void signInAnonymously() { // Given Mockito.doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) { ((FIRAuth.Block_signInAnonymouslyWithCompletion) invocation.getArgument(0)).call_signInAnonymouslyWithCompletion(null, null); return null; } }).when(firAuth).signInAnonymouslyWithCompletion(Mockito.any()); Auth auth = new Auth(); // When auth.signInAnonymously().subscribe(consumer); // Then Mockito.verify(firAuth, VerificationModeFactory.times(1)).signInAnonymouslyWithCompletion(Mockito.any()); Mockito.verify(consumer, VerificationModeFactory.times(1)).accept(Mockito.nullable(GdxFirebaseUser.class)); }
Example #20
Source File: RadlCreatorTest.java From RADL with Apache License 2.0 | 6 votes |
@Before public void init() throws CoreException { IProjectDescription description = mock(IProjectDescription.class); when(description.getBuildSpec()).thenReturn(new ICommand[0]); when(description.newCommand()).thenReturn(mock(ICommand.class)); when(description.getNatureIds()).thenReturn(natureIds.toArray(new String[natureIds.size()])); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { natureIds.clear(); natureIds.addAll(Arrays.asList((String[])invocation.getArguments()[0])); return null; } }).when(description).setNatureIds(any(String[].class)); when(project.getDescription()).thenReturn(description); when(folder.getProject()).thenReturn(project); when(folder.exists()).thenReturn(true); when(folder.getFile(anyString())).thenReturn(file); when(root.getFolder(new Path(folderName))).thenReturn(folder); }
Example #21
Source File: LocalityStoreTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Before public void setUp() { doReturn(mock(ChannelLogger.class)).when(helper).getChannelLogger(); doReturn(syncContext).when(helper).getSynchronizationContext(); doReturn(fakeClock.getScheduledExecutorService()).when(helper).getScheduledExecutorService(); when(orcaOobUtil.newOrcaReportingHelperWrapper(any(Helper.class), any(OrcaOobReportListener.class))) .thenAnswer(new Answer<OrcaReportingHelperWrapper>() { @Override public OrcaReportingHelperWrapper answer(InvocationOnMock invocation) { Helper h = invocation.getArgument(0); FakeOrcaReportingHelperWrapper res = new FakeOrcaReportingHelperWrapper(h); childHelperWrappers.put(h.getAuthority(), res); return res; } }); lbRegistry.register(lbProvider); localityStore = new LocalityStoreImpl(logId, helper, lbRegistry, random, loadStatsStore, orcaPerRequestUtil, orcaOobUtil); }
Example #22
Source File: DefaultConfigTest.java From apollo with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { MockInjector.setInstance(ConfigUtil.class, new MockConfigUtil()); propertiesFactory = mock(PropertiesFactory.class); when(propertiesFactory.getPropertiesInstance()).thenAnswer(new Answer<Properties>() { @Override public Properties answer(InvocationOnMock invocation) { return new Properties(); } }); MockInjector.setInstance(PropertiesFactory.class, propertiesFactory); someResourceDir = new File(ClassLoaderUtil.getClassPath() + "/META-INF/config"); someResourceDir.mkdirs(); someNamespace = "someName"; configRepository = mock(ConfigRepository.class); }
Example #23
Source File: PayPalUnitTest.java From braintree_android with MIT License | 6 votes |
@Test public void authorizeAccount_whenSuccessfulBrowserSwitch_sendsAnalyticsEvents() throws Exception { final BraintreeFragment fragment = mMockFragmentBuilder .successResponse(stringFromFixture("paypal_hermes_billing_agreement_response.json")) .build(); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) { Intent intent = new Intent() .setData(Uri.parse("com.braintreepayments.api.test.braintree://onetouch/v1/success?PayerID=HERMES-SANDBOX-PAYER-ID&paymentId=HERMES-SANDBOX-PAYMENT-ID&ba_token=EC-HERMES-SANDBOX-EC-TOKEN")); PayPal.onActivityResult(fragment, RESULT_OK, intent); return null; } }).when(fragment).browserSwitch(eq(BraintreeRequestCodes.PAYPAL), any(Intent.class)); MockStaticTokenizationClient.mockTokenizeSuccess(new PayPalAccountNonce()); PayPal.requestBillingAgreement(fragment, new PayPalRequest()); verify(fragment).sendAnalyticsEvent("paypal.billing-agreement.selected"); verify(fragment).sendAnalyticsEvent("paypal.billing-agreement.browser-switch.started"); verify(fragment).sendAnalyticsEvent("paypal.billing-agreement.browser-switch.succeeded"); }
Example #24
Source File: DummyCollaboratorCallerTest.java From Inside_Android_Testing with Apache License 2.0 | 6 votes |
@Test public void testDoSomethingAsynchronouslyUsingDoAnswer() { final List<String> results = Arrays.asList("One", "Two", "Three"); // Let's do a synchronous answer for the callback doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { ((DummyCallback)invocation.getArguments()[0]).onSuccess(results); return null; } }).when(mockDummyCollaborator).doSomethingAsynchronously(any(DummyCallback.class)); // Let's call the method under test dummyCaller.doSomethingAsynchronously(); // Verify state and interaction verify(mockDummyCollaborator, times(1)).doSomethingAsynchronously(any(DummyCallback.class)); assertThat(dummyCaller.getResult(), is(equalTo(results))); }
Example #25
Source File: HBaseConnectionPoolTest.java From pentaho-hadoop-shims with Apache License 2.0 | 6 votes |
@Test public void testConfigMessage() throws Exception { hBaseShim = mock( HBaseShim.class ); HBaseConnection hBaseConnection = mock( HBaseConnectionTestImpls.HBaseConnectionWithResultField.class ); when( hBaseShim.getHBaseConnection() ).thenReturn( hBaseConnection ); hBaseConnectionPool = new HBaseConnectionPool( hBaseShim, props, logChannelInterface, namedCluster ); final String message = "message"; doAnswer( new Answer<Void>() { @Override public Void answer( InvocationOnMock invocation ) throws Throwable { ( (List<String>) invocation.getArguments()[ 2 ] ).add( message ); return null; } } ).when( hBaseConnection ).configureConnection( eq( props ), eq( namedCluster ), anyList() ); hBaseConnectionPool.getConnectionHandle(); verify( logChannelInterface ).logBasic( message ); hBaseConnectionPool = new HBaseConnectionPool( hBaseShim, props, null, namedCluster ); hBaseConnectionPool.getConnectionHandle(); }
Example #26
Source File: VirtualMachineForOpenJ9Test.java From byte-buddy with Apache License 2.0 | 6 votes |
@Test public void testGetSystemProperties() throws Exception { Socket socket = mock(Socket.class); OutputStream outputStream = mock(OutputStream.class); when(socket.getOutputStream()).thenReturn(outputStream); InputStream inputStream = mock(InputStream.class); when(socket.getInputStream()).thenReturn(inputStream); when(inputStream.read(any(byte[].class))).then(new Answer<Integer>() { public Integer answer(InvocationOnMock invocation) throws Throwable { byte[] result = (FOO + "=" + BAR).getBytes("ISO_8859_1"); byte[] buffer = invocation.getArgument(0); System.arraycopy(result, 0, buffer, 0, result.length); buffer[result.length] = 0; return result.length + 1; } }); Properties properties = new VirtualMachine.ForOpenJ9(socket).getSystemProperties(); assertThat(properties.size(), is(1)); assertThat(properties.getProperty(FOO), is(BAR)); verify(outputStream).write("ATTACH_GETSYSTEMPROPERTIES".getBytes("UTF-8")); }
Example #27
Source File: RevisionManagerTest.java From alchemy with MIT License | 6 votes |
@Test public void testSetLatestRevision() { // our experiment will always be at revision Long.MIN_VALUE + 1 doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { final ExperimentEntity entity = mock(ExperimentEntity.class); entity.revision = Long.MIN_VALUE + 1; return entity; } }).when(ds).get(eq(ExperimentEntity.class), anyString()); final RevisionManager revisionManager = new RevisionManager(ds); revision = Long.MIN_VALUE; // our databases' revision revisionManager.setLatestRevision(Long.MIN_VALUE); // revision manager's internal revision assertFalse(revisionManager.checkIfAnyStale()); assertTrue(revisionManager.checkIfStale("foo")); revision = Long.MIN_VALUE + 1; // our databases' revision revisionManager.setLatestRevision(Long.MIN_VALUE); // revision manager's internal revision assertTrue(revisionManager.checkIfAnyStale()); revisionManager.setLatestRevision(Long.MIN_VALUE + 1); // revision manager's internal revision assertFalse(revisionManager.checkIfStale("foo")); }
Example #28
Source File: TestableDockerContainerWatchdog.java From docker-plugin with MIT License | 6 votes |
public static DockerAPI createMockedDockerAPI(List<Container> containerList) { DockerAPI result = Mockito.mock(DockerAPI.class); DockerClient client = Mockito.mock(DockerClient.class); Mockito.when(result.getClient()).thenReturn(client); DockerServerEndpoint dockerServerEndpoint = Mockito.mock(DockerServerEndpoint.class); Mockito.when(dockerServerEndpoint.getUri()).thenReturn("tcp://mocked-docker-host:2375"); Mockito.when(result.getDockerHost()).thenReturn(dockerServerEndpoint); ListContainersCmd listContainerCmd = Mockito.mock(ListContainersCmd.class); Mockito.when(client.listContainersCmd()).thenReturn(listContainerCmd); Mockito.when(listContainerCmd.withShowAll(true)).thenReturn(listContainerCmd); Mockito.when(listContainerCmd.withLabelFilter(Matchers.anyMap())).thenAnswer( new Answer<ListContainersCmd>() { @Override public ListContainersCmd answer(InvocationOnMock invocation) throws Throwable { Map<String, String> arg = invocation.getArgumentAt(0, Map.class); String jenkinsInstanceIdInFilter = arg.get(DockerContainerLabelKeys.JENKINS_INSTANCE_ID); Assert.assertEquals(UNITTEST_JENKINS_ID, jenkinsInstanceIdInFilter); return listContainerCmd; } }); Mockito.when(listContainerCmd.exec()).thenReturn(containerList); return result; }
Example #29
Source File: RouterTestBase.java From actframework with Apache License 2.0 | 6 votes |
@BeforeClass public static void prepareClass() throws Exception { AppConfig config = appConfig(); app = mock(App.class); when(app.config()).thenReturn(config); when(app.cuid()).thenReturn(S.random()); when(app.file(anyString())).thenAnswer(new Answer<File>() { @Override public File answer(InvocationOnMock invocation) throws Throwable { String path = (String) invocation.getArguments()[0]; return new File(BASE, path); } }); Field f = App.class.getDeclaredField("INST"); f.setAccessible(true); f.set(null, app); }
Example #30
Source File: GoogleAuthLibraryCallCredentialsTest.java From grpc-java with Apache License 2.0 | 6 votes |
@Before public void setUp() throws Exception { doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) { Credentials mock = (Credentials) invocation.getMock(); URI uri = (URI) invocation.getArguments()[0]; RequestMetadataCallback callback = (RequestMetadataCallback) invocation.getArguments()[2]; Map<String, List<String>> metadata; try { // Default to calling the blocking method, since it is easier to mock metadata = mock.getRequestMetadata(uri); } catch (Exception ex) { callback.onFailure(ex); return null; } callback.onSuccess(metadata); return null; } }).when(credentials).getRequestMetadata( any(URI.class), any(Executor.class), any(RequestMetadataCallback.class)); }