Refine search
public static <Solution_> InnerScoreDirector<Solution_> mockScoreDirector(SolutionDescriptor<Solution_> solutionDescriptor) { EasyScoreDirectorFactory<Solution_> scoreDirectorFactory = new EasyScoreDirectorFactory<>(solutionDescriptor, (EasyScoreCalculator<Solution_>) (solution_) -> SimpleScore.of(0)); scoreDirectorFactory.setInitializingScoreTrend( InitializingScoreTrend.buildUniformTrend(InitializingScoreTrendLevel.ONLY_DOWN, 1)); return mock(InnerScoreDirector.class, AdditionalAnswers.delegatesTo(scoreDirectorFactory.buildScoreDirector(false, false))); }
private static MacroInterpreter createMacroInterpreter() { MacroInterpreter macroInterpreter = mock(MacroInterpreter.class); doAnswer(returnsFirstArg()).when(macroInterpreter).interpret(anyString()); return macroInterpreter; } }
protected void blockDataContainerIteration(final Cache<?, ?> cache, final CyclicBarrier barrier) { InternalDataContainer dataContainer = TestingUtil.extractComponent(cache, InternalDataContainer.class); final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(dataContainer); InternalDataContainer mockContainer = mock(InternalDataContainer.class, withSettings().defaultAnswer(forwardedAnswer)); doAnswer(invocation -> { // Wait for main thread to sync up barrier.await(10, TimeUnit.SECONDS); // Now wait until main thread lets us through barrier.await(10, TimeUnit.SECONDS); return forwardedAnswer.answer(invocation); }).when(mockContainer).removeSegments(any()); TestingUtil.replaceComponent(cache, InternalDataContainer.class, mockContainer, true); } }
/** * Returns a mock unary operator that returns the elements of {@code values}. */ @SuppressWarnings("unchecked") public static @NotNull <E> UnaryOperator<E> mockUnaryOperatorMultipleAnswers(final @NotNull Iterable<E> values) { final UnaryOperator<E> operator = mock(UnaryOperator.class); when(operator.apply(any())) .thenAnswer(returnsElementsOf(Lists.newArrayList(values))); return operator; }
((SyncBeanManagerImpl) IOC.getBeanManager()).reset(); when(placeHistoryHandler.getPerspectiveFromPlace(any())).then(AdditionalAnswers.returnsFirstArg()); when(defaultPerspective.getIdentifier()) .thenReturn("DefaultPerspective"); when(defaultPerspective.isType(any(String.class))) .thenReturn(true); when(perspectiveManager.getCurrentPerspective()) return null; }).when(perspectiveManager).switchToPerspective(any(PlaceRequest.class), any(PerspectiveActivity.class), any(ParameterizedCommand.class)); return null; }).when(perspectiveManager).savePerspectiveState(any(Command.class)); doReturn(new DefaultPlaceRequest("lastPlaceRequest")) .when(defaultPerspective).getPlace(); doReturn(defaultPerspective).when(perspectiveManager) .getCurrentPerspective();
protected AsyncInterceptorChain mockEntrySet(final Cache<?, ?> cache, StreamMocking mocking) { AsyncInterceptorChain chain = TestingUtil.extractComponent(cache, AsyncInterceptorChain.class); AsyncInterceptorChain mockChain = spy(chain); doAnswer(i -> { CacheSet cacheSet = (CacheSet) i.callRealMethod(); CacheSet mockSet = mock(CacheSet.class, withSettings().defaultAnswer(delegatesTo(cacheSet))); when(mockSet.stream()).then(j -> { CacheStream stream = cacheSet.stream(); return mockStream(stream, mocking); }); return mockSet; }).when(mockChain).invoke(any(InvocationContext.class), any(EntrySetCommand.class)); TestingUtil.replaceComponent(cache, AsyncInterceptorChain.class, mockChain, true); return chain; } }
@Test public void testSplittableDoFnWithAllMethods() throws Exception { MockFn fn = mock(MockFn.class); DoFnInvoker<String, String> invoker = DoFnInvokers.invokerFor(fn); final SomeRestrictionTracker tracker = mock(SomeRestrictionTracker.class); final SomeRestrictionCoder coder = mock(SomeRestrictionCoder.class); SomeRestriction restriction = new SomeRestriction(); final SomeRestriction part1 = new SomeRestriction(); when(fn.getInitialRestriction("blah")).thenReturn(restriction); doAnswer( AdditionalAnswers.delegatesTo( new MockFn() { @DoFn.SplitRestriction .when(fn) .splitRestriction(eq("blah"), same(restriction), Mockito.any()); when(fn.newTracker(restriction)).thenReturn(tracker);
LocalStreamManager<Map.Entry<MagicKey, Object>, MagicKey> spiedManager = spy(localStreamManager); doAnswer(invocation -> { Object[] arguments = invocation.getArguments(); int offset = 8; TerminalOperation<Map.Entry<MagicKey, Object>, MagicKey> terminalOperation = (TerminalOperation) arguments[offset]; Answer opAnswer = AdditionalAnswers.delegatesTo(terminalOperation); TerminalOperation<Map.Entry<MagicKey, Object>, MagicKey> mockOperation = Mockito.mock(TerminalOperation.class, opAnswer); doAnswer(opInvocation -> { Answer supplierAnswer = AdditionalAnswers.delegatesTo(opInvocation.getArgument(0)); Supplier<Stream<Map.Entry<MagicKey, Object>>> mockSupplier = Mockito.mock(Supplier.class, supplierAnswer); doAnswer(blockingAnswer).when(mockSupplier).get(); }).when(mockOperation).setSupplier(any()); }).when(spiedManager).streamOperationRehashAware(any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), anyBoolean(), isA(SegmentRetryingOperation.class));
@Override protected Querier createQuerier(Querier.Mode mode, String id, String query, BulletConfig config) { Querier spied = spy(super.createQuerier(mode, id, query, config)); List<Boolean> answers = IntStream.range(0, doneAfter).mapToObj(i -> false) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); answers.add(true); doAnswer(returnsElementsOf(answers)).when(spied).isDone(); return spied; } }
protected void waitUntilNotificationRaised(final Cache<?, ?> cache, final CheckPoint checkPoint) { CacheNotifier cn = TestingUtil.extractComponent(cache, CacheNotifier.class); final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(cn); CacheNotifier mockNotifier = mock(CacheNotifier.class, withSettings().extraInterfaces(ClusterCacheNotifier.class) .defaultAnswer(forwardedAnswer)); Answer answer = invocation -> { // Wait for main thread to sync up checkPoint.trigger("pre_raise_notification_invoked"); // Now wait until main thread lets us through checkPoint.awaitStrict("pre_raise_notification_release", 10, TimeUnit.SECONDS); try { return forwardedAnswer.answer(invocation); } finally { // Wait for main thread to sync up checkPoint.trigger("post_raise_notification_invoked"); // Now wait until main thread lets us through checkPoint.awaitStrict("post_raise_notification_release", 10, TimeUnit.SECONDS); } }; doAnswer(answer).when(mockNotifier).notifyCacheEntryCreated(any(), any(), any(Metadata.class), eq(false), any(InvocationContext.class), any(FlagAffectedCommand.class)); doAnswer(answer).when(mockNotifier).notifyCacheEntryModified(any(), any(), any(Metadata.class), any(), any(Metadata.class), anyBoolean(), any(InvocationContext.class), any(FlagAffectedCommand.class)); doAnswer(answer).when(mockNotifier).notifyCacheEntryRemoved(any(), any(), any(Metadata.class), eq(false), any(InvocationContext.class), any(FlagAffectedCommand.class)); TestingUtil.replaceComponent(cache, CacheNotifier.class, mockNotifier, true); }
@Before public void setUp() { fundRepository = mock(FundRepository.class); refundRepository = mock(RefundRepository.class); pendingFundRepository = mock(PendingFundRepository.class); requestRepository = mock(RequestRepository.class); mappers = mock(Mappers.class); fundRequestContractsService = mock(FundRequestContractsService.class, RETURNS_DEEP_STUBS); fiatService = mock(FiatService.class); when(fundRepository.saveAndFlush(any(Fund.class))).then(returnsFirstArg()); funder = UserProfileMother.davy()::getId; tokenValueMapper = mock(TokenValueMapper.class); fundsAndRefundsAggregator); when(fundRepository.saveAndFlush(any(Fund.class))).then(returnsFirstArg());
MockSettings settings = withSettings() .defaultAnswer(RETURNS_DEFAULTS); instance = mock(field.getType(), settings); } else { instance = mock(field.getType(), delegatesTo(instance)); instance = mock(field.getType(), delegatesTo(instance));
private void setUpResourceService() { when(mockResourceService.get(eq(identifier))).thenAnswer(inv -> completedFuture(mockResource)); when(mockResourceService.get(eq(rdf.createIRI(TRELLIS_DATA_PREFIX + "resource")))) .thenAnswer(inv -> completedFuture(mockResource)); when(mockResourceService.get(eq(root))).thenAnswer(inv -> completedFuture(mockRootResource)); when(mockResourceService.replace(any(Metadata.class), any(Dataset.class))).thenReturn(completedFuture(null)); when(mockResourceService.create(any(Metadata.class), any(Dataset.class))).thenReturn(completedFuture(null)); when(mockResourceService.unskolemize(any(Literal.class))).then(returnsFirstArg()); when(mockResourceService.skolemize(any(Literal.class))).then(returnsFirstArg()); when(mockResourceService.skolemize(any(IRI.class))).then(returnsFirstArg()); when(mockResourceService.skolemize(any(BlankNode.class))).thenAnswer(inv -> rdf.createIRI(TRELLIS_BNODE_PREFIX + ((BlankNode) inv.getArgument(0)).uniqueReference()));
@Test public void createWithNewIssue() { CreateRequestCommand command = createCommand(); when(requestRepository.findByPlatformAndPlatformId(command.getPlatform(), command.getPlatformId())).thenReturn(Optional.empty()); IssueInformation issueInformation = IssueInformationMother.kazuki43zooApiStub().build(); when(githubLinkParser.parseIssue(command.getPlatformId())).thenReturn(issueInformation); when(requestRepository.save(any(Request.class))).then(returnsFirstArg()); requestService.createRequest(command); ArgumentCaptor<Request> savedRequest = ArgumentCaptor.forClass(Request.class); verify(requestRepository).save(savedRequest.capture()); assertThat(savedRequest.getValue().getIssueInformation()).isEqualTo(issueInformation); assertThat(savedRequest.getValue().getStatus()).isEqualTo(RequestStatus.OPEN); assertThat(savedRequest.getValue().getType()).isEqualTo(RequestType.ISSUE); }
@Before public void setUp() throws MuleException { when(streamingManager.manage(any(CursorProvider.class), any(CoreEvent.class))).then(returnsFirstArg()); expressionManager = new DefaultExpressionManager(); initialiseIfNeeded(expressionManager, muleContext); }
}; given(dexFileLoader.loadDex(anyString(), anyString())) .will(answer((src, out) -> { dalvik.system.DexFile file = mock(dalvik.system.DexFile.class, withSettings().stubOnly()); given(file.loadClass(anyString(), eq(loader))).willReturn(MyClass.class); return file; assertSame(MyClass.class, classPath.loadClass(className, loader)); then(executor).should(times(2)).execute(any(RunnableFuture.class));
private void setUpResourceService() { when(mockResourceService.supportedInteractionModels()).thenReturn(allInteractionModels); when(mockResourceService.get(any(IRI.class))).thenAnswer(inv -> completedFuture(mockResource)); when(mockResourceService.create(any(Metadata.class), any(Dataset.class))).thenReturn(completedFuture(null)); when(mockResourceService.replace(any(Metadata.class), any(Dataset.class))).thenReturn(completedFuture(null)); when(mockResourceService.delete(any(Metadata.class))).thenReturn(completedFuture(null)); when(mockResourceService.add(any(IRI.class), any(Dataset.class))).thenReturn(completedFuture(null)); when(mockResourceService.skolemize(any(Literal.class))).then(returnsFirstArg()); when(mockResourceService.skolemize(any(IRI.class))).then(returnsFirstArg()); when(mockResourceService.skolemize(any(BlankNode.class))).thenAnswer(inv -> rdf.createIRI(TRELLIS_BNODE_PREFIX + ((BlankNode) inv.getArgument(0)).uniqueReference())); when(mockResourceService.toInternal(any(RDFTerm.class), any())).thenCallRealMethod(); when(mockResourceService.toExternal(any(RDFTerm.class), any())).thenCallRealMethod(); when(mockResourceService.touch(any(IRI.class))).thenReturn(completedFuture(null)); }
new MessagingMethodInvokerHelper<>(bean, UseSpelInvokerBean.class.getDeclaredMethod("foo", String.class), false); helper.setBeanFactory(mock(BeanFactory.class)); Message<?> message = new GenericMessage<>("Test"); helper.process(message); helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); assertEquals(SpelCompilerMode.IMMEDIATE, helper.setBeanFactory(mock(BeanFactory.class)); helper.process(message); assertEquals(SpelCompilerMode.MIXED, UseSpelInvokerBean.class.getDeclaredMethod("buz", String.class), false); ConfigurableListableBeanFactory bf = mock(ConfigurableListableBeanFactory.class); willAnswer(returnsFirstArg()).given(bf).resolveEmbeddedValue(anyString()); helper.setBeanFactory(bf); try {
@Test public void should_generate_non_final_classes() throws IOException { ImmutableClassDef def = new ImmutableClassDef("Lfoo/Bar;", AccessFlags.FINAL.getValue(), "Ljava/lang/Object;", null, null, null, null, null); byte[] bytes = DexPoolUtils.toBytecode(new ImmutableDexFile(Opcodes.getDefault(), Collections.singleton(def))); given(dexFileLoader.loadDex(srcPathCaptor.capture(), anyString())) .will(answer((String src, String out) -> { assertTrue(src.endsWith("tmp.dex")); assertTrue(out.endsWith(".dex")); DexFile file; try (InputStream in = new FileInputStream(src)) { file = new DexBackedDexFile(null, ByteStreams.toByteArray(in)); } Set<? extends ClassDef> classes = file.getClasses(); assertSame(1, classes.size()); assertFalse(AccessFlags.FINAL.isSet(classes.iterator().next().getAccessFlags())); return dexFile; })); DexFile file = new DexBackedDexFile(null, bytes); ClassTransformer transformer = new ClassTransformer(file.getOpcodes(), file.getClasses(), folder.newFolder(), dexFileLoader); assertSame(dexFile, transformer.call()); assertTrue(transformer.getClasses().isEmpty()); assertFalse(new File(srcPathCaptor.getValue()).exists()); }
private void blockRebalanceConfirmation(final EmbeddedCacheManager manager, final CheckPoint checkPoint, int rebalanceTopologyId) throws Exception { ClusterTopologyManager ctm = TestingUtil.extractGlobalComponent(manager, ClusterTopologyManager.class); final Answer<Object> forwardedAnswer = AdditionalAnswers.delegatesTo(ctm); ClusterTopologyManager mockManager = mock(ClusterTopologyManager.class, withSettings().defaultAnswer(forwardedAnswer)); doAnswer(invocation -> { Object[] arguments = invocation.getArguments(); Address source = (Address) arguments[1]; int topologyId = (Integer) arguments[2]; if (topologyId == rebalanceTopologyId) { checkPoint.trigger("pre_rebalance_confirmation_" + topologyId + "_from_" + source); checkPoint.awaitStrict("resume_rebalance_confirmation_" + topologyId + "_from_" + source, 20, SECONDS); } return forwardedAnswer.answer(invocation); }).when(mockManager).handleRebalancePhaseConfirm(anyString(), any(Address.class), anyInt(), isNull(), anyInt()); TestingUtil.replaceComponent(manager, ClusterTopologyManager.class, mockManager, true); }