Refine search
/** * Add real map behavior to a mock region. Useful for tests where you want to mock region that * just behaves like a map. * * @param mock the mockito mock to add behavior too. */ public static void addMapBehavior(Region mock) { // Allow the region to behave like a fake map Map underlyingMap = new HashMap(); when(mock.get(any())).then(invocation -> underlyingMap.get(invocation.getArguments()[0])); when(mock.put(any(), any())).then(invocation -> underlyingMap.put(invocation.getArguments()[0], invocation.getArguments()[1])); }
@Before public void setUp() throws Exception { data.groupMeta = groupMeta; when( groupMeta.size() ).thenReturn( 1 ); when( groupMeta.getValueMeta( anyInt() ) ).thenReturn( valueMeta ); when( valueMeta.convertToNormalStorageType( anyObject() ) ).then( new Answer<Object>() { @Override public Object answer( InvocationOnMock invocation ) throws Throwable { Object argument = invocation.getArguments()[0]; return new String( (byte[]) argument ); } } ); }
@Before public void setUp() { cache = mock(InternalCacheForClientAccess.class); doReturn(cache).when(cache).getCacheForProcessingClientRequests(); region = mock(Region.class); when(cache.getRegion(REGION)).thenReturn(region); security = mock(Security.class); doThrow(NotAuthorizedException.class).when(security).authorize(any()); doThrow(NotAuthorizedException.class).when(security).authorize(any(), any(), any(), any()); when(security.postProcess(any(), any(), any())).then(invocation -> invocation.getArgument(2)); when(security.needsPostProcessing()).thenReturn(true); authorizingCache = new SecureCacheImpl(cache, security); }
private void recordEntityEventsToList(EntityRef entityRefMock, List<Event> listToFill) { Mockito.when(entityRefMock.send(Mockito.any())).then(new Answer<Event>() { @Override public Event answer(InvocationOnMock invocation) throws Throwable { Event event = invocation.getArgument(0); listToFill.add(event); return event; } }); }
@Test public void shouldBlockUntilTheIndexIsOnline() throws IndexNotFoundKernelException, InterruptedException { when( tokenRead.nodeLabel( anyString() ) ).thenReturn( 0 ); when( tokenRead.propertyKey( anyString() ) ).thenReturn( 0 ); when( schemaRead.index( anyInt(), any() ) ).thenReturn( anyIndex ); AtomicReference<InternalIndexState> state = new AtomicReference<>( POPULATING ); when( schemaRead.indexGetState( any( IndexReference.class ) ) ).then( invocationOnMock -> state.get() ); AtomicBoolean done = new AtomicBoolean( false ); new Thread( () -> { try { procedure.awaitIndexByPattern( ":Person(name)", TIMEOUT, TIME_UNIT ); } catch ( ProcedureException e ) { throw new RuntimeException( e ); } done.set( true ); } ).start(); assertThat( done.get(), is( false ) ); state.set( ONLINE ); assertEventually( "Procedure did not return after index was online", done::get, is( true ), TIMEOUT, TIME_UNIT ); }
private static TransactionCommitProcess newRememberingCommitProcess( final TransactionRepresentation[] slot ) throws TransactionFailureException { TransactionCommitProcess commitProcess = mock( TransactionCommitProcess.class ); when( commitProcess.commit( any( TransactionToApply.class ), any( CommitEvent.class ), any( TransactionApplicationMode.class ) ) ) .then( invocation -> { slot[0] = ((TransactionToApply) invocation.getArgument( 0 )).transactionRepresentation(); return 1L; } ); return commitProcess; }
@Test @SuppressWarnings("unchecked") public void testGetMisses() throws Exception { when(numberAuthoritativeTier.getAndFault(eq(1))).thenReturn(null); when(numberCachingTier.getOrComputeIfAbsent(any(Number.class), any(Function.class))).then((Answer<Store.ValueHolder<CharSequence>>) invocation -> { Number key = (Number) invocation.getArguments()[0]; Function<Number, Store.ValueHolder<CharSequence>> function = (Function<Number, Store.ValueHolder<CharSequence>>) invocation.getArguments()[1]; return function.apply(key); }); TieredStore<Number, CharSequence> tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); assertThat(tieredStore.get(1), is(nullValue())); verify(numberCachingTier, times(1)).getOrComputeIfAbsent(eq(1), any(Function.class)); verify(numberAuthoritativeTier, times(1)).getAndFault(any(Number.class)); }
/** * Expectation setter for multiple reads where each one reads random bytes to the buffer. * * @param channelMock The mocked FileChannel object * @param bufferSize The buffer size * @return Expected buffer string * @throws IOException If an I/O error occurs */ private String fileChannelMockExpectReadWithRandomBytes(final FileChannel channelMock, final int bufferSize) throws IOException { final int step = 20; final Random random = new Random(); int remainingBytes = bufferSize; OngoingStubbing<Integer> when = when(channelMock.read(any(), anyLong())); StringBuilder expectedBufferContent = new StringBuilder(); while (remainingBytes > 0) { final int bytesRead = remainingBytes < step ? remainingBytes : random.nextInt(step); final String stringRead = IntStream.range(0, bytesRead).mapToObj(i -> "a").collect(Collectors.joining()); expectedBufferContent.append(stringRead); when = when.then(invocation -> { ByteBuffer buffer = invocation.getArgument(0); buffer.put(stringRead.getBytes()); return bytesRead; }); remainingBytes -= bytesRead; } return expectedBufferContent.toString(); }
@Test public void shouldOpenTheNextChannelWhenItExists() throws IOException { // given final StoreChannel newStoreChannel = mock( StoreChannel.class ); final ReaderLogVersionBridge bridge = new ReaderLogVersionBridge( logFiles ); when( channel.getVersion() ).thenReturn( version ); when( channel.getLogFormatVersion() ).thenReturn( CURRENT_LOG_VERSION ); when( fs.fileExists( any( File.class ) ) ).thenReturn( true ); when( fs.open( any( File.class ), eq( OpenMode.READ ) ) ).thenReturn( newStoreChannel ); when( newStoreChannel.read( ArgumentMatchers.<ByteBuffer>any() ) ).then( invocationOnMock -> { ByteBuffer buffer = invocationOnMock.getArgument( 0 ); buffer.putLong( encodeLogVersion( version + 1 ) ); buffer.putLong( 42 ); return LOG_HEADER_SIZE; } ); // when final LogVersionedStoreChannel result = bridge.next( channel ); // then PhysicalLogVersionedStoreChannel expected = new PhysicalLogVersionedStoreChannel( newStoreChannel, version + 1, CURRENT_LOG_VERSION ); assertEquals( expected, result ); verify( channel, times( 1 ) ).close(); }
private void createServerApiMock() { serverAPIMock = mock(ServerAPI.class); when(serverAPIMock.getItems(anyString(), anyString())).then(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { ServerAPI.Response response = new ServerAPI.Response(); response.items = new ServerAPI.Item[]{new ServerAPI.Item(TEST_TEXT)}; return Observable.just(response); } }); }
@Test public void shouldResendDescriptorWhenSendFails() { final long fromRecordingId = 1; final ListRecordingsSession session = new ListRecordingsSession( correlationId, fromRecordingId, 1, catalog, controlResponseProxy, controlSession, descriptorBuffer); when(controlSession.sendDescriptor(eq(correlationId), any(), eq(controlResponseProxy))).thenReturn(0); session.doWork(); verify(controlSession, times(1)).sendDescriptor(eq(correlationId), any(), eq(controlResponseProxy)); final MutableLong counter = new MutableLong(fromRecordingId); when(controlSession.sendDescriptor(eq(correlationId), any(), eq(controlResponseProxy))) .then(verifySendDescriptor(counter)); session.doWork(); verify(controlSession, times(2)).sendDescriptor(eq(correlationId), any(), eq(controlResponseProxy)); }
@Test public void testReadFullyIfEofIsReached() throws IOException { final FileChannel channelMock = mock(FileChannel.class); final int bufferSize = 100; final String fileChannelContent = "abcdefghkl"; ByteBuffer buffer = ByteBuffer.allocate(bufferSize); when(channelMock.read(any(), anyLong())).then(invocation -> { ByteBuffer bufferArg = invocation.getArgument(0); bufferArg.put(fileChannelContent.getBytes()); return -1; }); Utils.readFully(channelMock, buffer, 0L); assertEquals("abcdefghkl", new String(buffer.array(), 0, buffer.position())); assertEquals(fileChannelContent.length(), buffer.position()); assertTrue(buffer.hasRemaining()); verify(channelMock, atLeastOnce()).read(any(), anyLong()); }
@Test @SuppressWarnings("unchecked") public void testGetHitsAuthoritativeTier() throws Exception { Store.ValueHolder<CharSequence> valueHolder = newValueHolder("one"); when(numberAuthoritativeTier.getAndFault(eq(1))).thenReturn(valueHolder); when(numberCachingTier.getOrComputeIfAbsent(any(Number.class), any(Function.class))).then((Answer<Store.ValueHolder<CharSequence>>) invocation -> { Number key = (Number) invocation.getArguments()[0]; Function<Number, Store.ValueHolder<CharSequence>> function = (Function<Number, Store.ValueHolder<CharSequence>>) invocation.getArguments()[1]; return function.apply(key); }); TieredStore<Number, CharSequence> tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); assertThat(tieredStore.get(1).get(), Matchers.equalTo("one")); verify(numberCachingTier, times(1)).getOrComputeIfAbsent(eq(1), any(Function.class)); verify(numberAuthoritativeTier, times(1)).getAndFault(any(Number.class)); }
@Test(expected = InvalidReceiveException.class) public void testOversizeRequest() throws IOException { TransportLayer transportLayer = mock(TransportLayer.class); Map<String, ?> configs = Collections.singletonMap(BrokerSecurityConfigs.SASL_ENABLED_MECHANISMS_CONFIG, Collections.singletonList(SCRAM_SHA_256.mechanismName())); SaslServerAuthenticator authenticator = setupAuthenticator(configs, transportLayer, SCRAM_SHA_256.mechanismName()); when(transportLayer.read(any(ByteBuffer.class))).then(invocation -> { invocation.<ByteBuffer>getArgument(0).putInt(SaslServerAuthenticator.MAX_RECEIVE_SIZE + 1); return 4; }); authenticator.authenticate(); verify(transportLayer).read(any(ByteBuffer.class)); }
@Test public void createMissingBucket() throws BucketNotFoundException { setUpMockBucket(0); when(fileDataStore.getLocalBucketById(eq(0))).thenReturn(null); when(fileAndChunkRegion.getOrCreateNodeForBucketWrite(eq(0), (RetryTimeKeeper) any())) .then(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { when(fileDataStore.getLocalBucketById(eq(0))).thenReturn(fileAndChunkBuckets.get(0)); return null; } }); assertNotNull(repoManager.getRepository(userRegion, 0, null)); }
private void mockRead(final PartialResultSet myResultSet) { final ArgumentCaptor<SpannerRpc.ResultStreamConsumer> consumer = ArgumentCaptor.forClass(SpannerRpc.ResultStreamConsumer.class); Mockito.when(rpc.read(Mockito.<ReadRequest>any(), consumer.capture(), Mockito.eq(options))) .then( new Answer<SpannerRpc.StreamingCall>() { @Override public SpannerRpc.StreamingCall answer(InvocationOnMock invocation) throws Throwable { consumer.getValue().onPartialResultSet(myResultSet); consumer.getValue().onCompleted(); return new NoOpStreamingCall(); } }); }
private void mockPublication(final ExclusivePublication replay, final UnsafeBuffer termBuffer) { when(replay.tryClaim(anyInt(), any(BufferClaim.class))).then( (invocation) -> { final int claimedSize = invocation.getArgument(0); final BufferClaim buffer = invocation.getArgument(1); buffer.wrap(termBuffer, messageCounter * FRAME_LENGTH, claimedSize + HEADER_LENGTH); messageCounter++; return (long)claimedSize; }); when(replay.appendPadding(anyInt())).then( (invocation) -> { final int claimedSize = invocation.getArgument(0); messageCounter++; return (long)claimedSize; }); }
public HStore createStoreMock(String name) throws Exception { HStore store = mock(HStore.class, name); when(store.requestCompaction(anyInt(), any(), any())).then(inv -> selectCompaction()); when(store.getCompactPriority()).then(inv -> getPriority()); doAnswer(new CancelAnswer()).when(store).cancelRequestedCompaction(any()); return store; } }
@Test @SuppressWarnings("unchecked") public void testCompute3Args() throws Exception { when(numberAuthoritativeTier.computeAndGet(any(Number.class), any(BiFunction.class), any(Supplier.class), any(Supplier.class))).then((Answer<Store.ValueHolder<CharSequence>>) invocation -> { Number key = (Number) invocation.getArguments()[0]; BiFunction<Number, CharSequence, CharSequence> function = (BiFunction<Number, CharSequence, CharSequence>) invocation.getArguments()[1]; return newValueHolder(function.apply(key, null)); }); TieredStore<Number, CharSequence> tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); assertThat(tieredStore.computeAndGet(1, (number, charSequence) -> "one", () -> true, () -> false).get(), Matchers.<CharSequence>equalTo("one")); verify(numberCachingTier, times(1)).invalidate(any(Number.class)); verify(numberAuthoritativeTier, times(1)).computeAndGet(eq(1), any(BiFunction.class), any(Supplier.class), any(Supplier.class)); }