@Test public void deferredQueryWithSingleResult() { EntityManagerFactory emf = mock(EntityManagerFactory.class); EntityManager targetEm = mock(EntityManager.class); Query query = mock(Query.class); given(emf.createEntityManager()).willReturn(targetEm); given(targetEm.createQuery("x")).willReturn(query); given(targetEm.isOpen()).willReturn(true); EntityManager em = SharedEntityManagerCreator.createSharedEntityManager(emf); em.createQuery("x").getSingleResult(); verify(query).getSingleResult(); verify(targetEm).close(); }
@Test public void testCouldNotClose() throws Exception { SQLException sqlException = new SQLException("bar"); given(this.connection.createStatement()).willReturn(this.statement); given(this.resultSet.next()).willReturn(false); willThrow(sqlException).given(this.resultSet).close(); willThrow(sqlException).given(this.statement).close(); willThrow(sqlException).given(this.connection).close(); RowCountCallbackHandler rcch = new RowCountCallbackHandler(); this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch); verify(this.connection).close(); }
@Before public void setup() { this.session = mock(Session.class); given(this.session.getUpgradeRequest()).willReturn(Mockito.mock(UpgradeRequest.class)); given(this.session.getUpgradeResponse()).willReturn(Mockito.mock(UpgradeResponse.class)); this.webSocketHandler = mock(WebSocketHandler.class); this.webSocketSession = new JettyWebSocketSession(null, null); this.adapter = new JettyWebSocketHandlerAdapter(this.webSocketHandler, this.webSocketSession); }
protected final ContentHandler mockContentHandler() throws Exception { ContentHandler contentHandler = mock(ContentHandler.class); willAnswer(new CopyCharsAnswer()).given(contentHandler).characters(any(char[].class), anyInt(), anyInt()); willAnswer(new CopyCharsAnswer()).given(contentHandler).ignorableWhitespace(any(char[].class), anyInt(), anyInt()); willAnswer(new Answer<Object>() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { invocation.getArguments()[3] = new AttributesImpl((Attributes) invocation.getArguments()[3]); return null; } }).given(contentHandler).startElement(anyString(), anyString(), anyString(), any(Attributes.class)); return contentHandler; }
private void doSkipImmutableValue(Object immutableValue) { HttpServletRequest request = mock(HttpServletRequest.class); HttpSession session = mock(HttpSession.class); given(request.getSession(anyBoolean())).willReturn(session); given(session.getAttribute(KEY)).willReturn(immutableValue); ServletRequestAttributes attrs = new ServletRequestAttributes(request); attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION); attrs.requestCompleted(); verify(session, times(2)).getAttribute(KEY); verifyNoMoreInteractions(session); }
@Test public void testSunnyDayPathLogsCorrectly() throws Throwable { MethodInvocation methodInvocation = mock(MethodInvocation.class); given(methodInvocation.getMethod()).willReturn(String.class.getMethod("toString")); given(methodInvocation.getThis()).willReturn(this); Log log = mock(Log.class); given(log.isTraceEnabled()).willReturn(true); CustomizableTraceInterceptor interceptor = new StubCustomizableTraceInterceptor(log); interceptor.invoke(methodInvocation); verify(log, times(2)).trace(anyString()); }
@Override @Before public void setUp() throws Exception { super.setUp(); session = MgnlContext.getJCRSession(RepositoryConstants.WEBSITE); Node node = session.getRootNode().addNode("testNode", NodeTypes.ContentNode.NAME); registryFacade = mock(RegistryFacade.class); Registry registry = mock(Registry.class); DefinitionProvider definitionProvider = mock(DefinitionProvider.class); DefinitionMetadata definitionMetadata = mock(DefinitionMetadata.class); given(definitionProvider.getMetadata()).willReturn(definitionMetadata); given(registry.getAllProviders()).willReturn(newArrayList(definitionProvider)); given(registryFacade.all()).willReturn(Arrays.asList(registry)); given(definitionProvider.getMetadata().getLocation()).willReturn(node.getPath()); rule = new IsDefinitionRule(registryFacade); }
@Test(expected = Test.None.class) public void deletedItemSelectionDoesNotThrowException() { // GIVEN given(activeContentPresenter.getSelectedItemIds()).willReturn(Lists.<Object>newArrayList("/b")); given(contentConnector.canHandleItem("/b")).willReturn(false); given(contentConnector.getItemUrlFragment("/b")).willThrow(Exception.class); // WHEN barPresenter.refresh(); }
@Override @Before public void setUp() throws Exception { super.setUp(); Session session = MgnlContext.getJCRSession(RepositoryConstants.WEBSITE); root = session.getRootNode(); properties = mock(MagnoliaConfigurationProperties.class); WorkspaceMapping workspaceMapping = mock(WorkspaceMapping.class); given(workspaceMapping.getLogicalWorkspaceNames()).willReturn(newArrayList("website")); Provider provider = mock(Provider.class); given(workspaceMapping.getRepositoryProvider(anyString())).willReturn(provider); RepositoryDefinition repositoryDefinition = mock(RepositoryDefinition.class); Map<String, String> definitionMap = newHashMap(); definitionMap.put("website", "website"); given(repositoryDefinition.getParameters()).willReturn(definitionMap); given(repositoryDefinition.getWorkspaces()).willReturn(newArrayList("website")); given(workspaceMapping.getRepositoryDefinitions()).willReturn(newArrayList(repositoryDefinition)); DefaultRepositoryManager repositoryManager = new DefaultRepositoryManager(properties, workspaceMapping); repoMan = Components.getComponent(RepositoryManager.class); ComponentsTestUtil.setInstance(RepositoryManager.class, repositoryManager); }
@Before public void setUp() throws Exception { registryFacade = mock(RegistryFacade.class); Registry registry = mock(Registry.class); outputStream = new ByteArrayOutputStream(); context = new MockContext(); cmd = new ExportJcrNodeToYamlCommand(registryFacade, new DefinitionRawViewToYamlConverterImpl()); MgnlContext.setInstance(context); MockSession webSiteSession = new MockSession("website"); context.addSession("website", webSiteSession); toCopyNode = webSiteSession.getRootNode().addNode("toCopy"); definitionProvider = mock(DefinitionProvider.class); DefinitionMetadata definitionMetadata = mock(DefinitionMetadata.class); given(definitionProvider.getMetadata()).willReturn(definitionMetadata); given(definitionProvider.getMetadata().getLocation()).willReturn(toCopyNode.getPath()); given(registry.getAllProviders()).willReturn(newArrayList(definitionProvider)); doReturn(Arrays.asList(registry)).when(registryFacade).all(); accessManager = mock(AccessManager.class); context.setAccessManager(accessManager); when(accessManager.isGranted(anyString(), eq(Permission.READ))).thenReturn(true); cmd.setOutputStream(outputStream); cmd.setPath(toCopyNode.getPath()); cmd.setRepository(RepositoryConstants.WEBSITE); }
super.setUp(); Context systemContext = spy(MgnlContext.getInstance()); MgnlContext.setInstance(systemContext); AccessManager ami = mock(AccessManager.class); doReturn(true).when(ami).isGranted(anyString(), anyLong()); doReturn(ami).when(systemContext).getAccessManager(anyString()); context = mock(Context.class); given(context.get(MarkNodeAsDeletedCommand.DELETED_NODE_PROP_NAME)).willReturn("rootFolder"); given(context.containsKey(RestorePreviousVersionCommand.ATTRIBUTE_PARENT_NODE_TYPE_ONLY)).willReturn(true); given(context.get(RestorePreviousVersionCommand.ATTRIBUTE_PARENT_NODE_TYPE_ONLY)).willReturn(true); ActivationManager activationManager = mock(ActivationManager.class); Subscriber subscriber = mock(Subscriber.class); Collection<Subscriber> subscribers = Lists.newArrayList(subscriber); ComponentsTestUtil.setInstance(ActivationManager.class, activationManager); given(activationManager.getSubscribers()).willReturn(subscribers); given(subscriber.isActive()).willReturn(true);
@Test public void testProcessShouldDoNothingWhenResponseFISCompressionIsNotNeeded() { //GIVEN given(resp.getContentType()).willReturn("html"); given(req.getHeader(ACCEPT_HEADER_KEY)).willReturn(ACCEPT_VALUE_XML); //WHEN underTest.process(req, resp, RESPONSE_BODY.getBytes()); //THEN verify(fastInfosetCompressor, times(0)).compress(any(ByteArrayInputStream.class)); verify(resp, times(0)).setHeader(ACCEPT_HEADER_KEY, ACCEPT_VALUE_FASTINFOSET); }
@Test public void contentChangedEventCheckIfItemCanBeHandledByContentConnector() throws Exception { // GIVEN given(contentConnector.canHandleItem(node.getIdentifier())).willReturn(true); given(contentConnector.getItem(anyObject())).willReturn(null); given(presenter.getSelectedItemIds()).willReturn(Lists.<Object>newArrayList(node.getIdentifier())); // Save the deletion request. node.remove(); session.save(); // WHEN admincentralEventBus.fireEvent(new ContentChangedEvent(node.getIdentifier())); // THEN verify(workbenchPresenter).select(eq(Collections.emptyList())); } }
@SuppressWarnings("unchecked") @Test public void testBatchFilter() throws Exception { BatchAcknowledgingMessageListener<String, String> listener = mock(BatchAcknowledgingMessageListener.class); FilteringBatchMessageListenerAdapter<String, String> adapter = new FilteringBatchMessageListenerAdapter<String, String>(listener, r -> false); List<ConsumerRecord<String, String>> consumerRecords = new ArrayList<>(); final CountDownLatch latch = new CountDownLatch(1); willAnswer(i -> { latch.countDown(); return null; }).given(listener).onMessage(any(List.class), any(Acknowledgment.class)); Acknowledgment ack = mock(Acknowledgment.class); adapter.onMessage(consumerRecords, ack, null); assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue(); verify(ack, never()).acknowledge(); }
@Test public void shouldFilterOutRecordsBeforeOrAtCheckpoint() { given(checkpoint.isBeforeOrAt(record1)).willReturn(false); given(checkpoint.isBeforeOrAt(record2)).willReturn(true); given(checkpoint.isBeforeOrAt(record3)).willReturn(true); given(checkpoint.isBeforeOrAt(record4)).willReturn(false); given(checkpoint.isBeforeOrAt(record5)).willReturn(true); List<KinesisRecord> records = Lists.newArrayList(record1, record2, record3, record4, record5); RecordFilter underTest = new RecordFilter(); List<KinesisRecord> retainedRecords = underTest.apply(records, checkpoint); Assertions.assertThat(retainedRecords).containsOnly(record2, record3, record5); }
@Test public void shouldMapAllShardsToCheckpoints() throws Exception { given(shard1.getShardId()).willReturn("shard-01"); given(shard2.getShardId()).willReturn("shard-02"); given(shard3.getShardId()).willReturn("shard-03"); Set<Shard> shards = Sets.newHashSet(shard1, shard2, shard3); StartingPoint startingPoint = new StartingPoint(InitialPositionInStream.LATEST); given( startingPointShardsFinder.findShardsAtStartingPoint( kinesisClient, "stream", startingPoint)) .willReturn(shards); DynamicCheckpointGenerator underTest = new DynamicCheckpointGenerator("stream", startingPoint, startingPointShardsFinder); KinesisReaderCheckpoint checkpoint = underTest.generate(kinesisClient); assertThat(checkpoint).hasSize(3); }
@Test public void argumentsConverterFails() throws Exception { PropertyResolveRequest propertyResolveRequest = mock(PropertyResolveRequest.class, RETURNS_DEEP_STUBS); given(propertyResolveRequest.getArguments()).willReturn(asList()); given(argumentsConverter.convert(eq(javaMethod), argThat(arrayWithSize(0)))).willReturn(Optional.<Object[]>absent()); Optional<Value> result = underTest.resolve(propertyResolveRequest); assertEquals(Optional.<Value>absent(), result); }
@Test public void testDefaultLayoutType() throws IOException, URISyntaxException { NFSv41DeviceManager dm = mock(NFSv41DeviceManager.class); RpcCall call = mock(RpcCall.class); RpcTransport transport = mock(RpcTransport.class); ExportFile exportFile = new ExportFile(ClassLoader.getSystemResource("org/dcache/nfs/exports").toURI()); given(dm.getLayoutTypes()).willReturn(Sets.newHashSet(layouttype4.values())); given(transport.getRemoteSocketAddress()).willReturn(new InetSocketAddress("172.16.4.1", 0)); given(call.getCredential()).willReturn(new RpcAuthTypeNone()); given(call.getTransport()).willReturn(transport); CompoundContext context = new CompoundContextBuilder() .withDeviceManager(dm) .withCall(call) .withExportFile(exportFile) .build(); Optional<fattr4_fs_layout_types> res = (Optional<fattr4_fs_layout_types>) OperationGETATTR.fattr2xdr(nfs4_prot.FATTR4_FS_LAYOUT_TYPES, null, null, null, context); assertArrayEquals("export without explicit layout type must return nfsv41_files layout", new int[] {layouttype4.LAYOUT4_NFSV4_1_FILES.getValue()}, res.get().value); }
@Test public void testAutoCreateChannel() { ConfigurableListableBeanFactory beanFactory = mock(ConfigurableListableBeanFactory.class, withSettings().extraInterfaces(BeanDefinitionRegistry.class)); given(beanFactory.getBean("channel", MessageChannel.class)).willThrow(NoSuchBeanDefinitionException.class); willAnswer(invocation -> invocation.getArgument(0)) .given(beanFactory).initializeBean(any(DirectChannel.class), eq("channel")); willAnswer(invocation -> invocation.getArgument(0)) .given(beanFactory).initializeBean(any(MessageHandler.class), eq("foo.foo.serviceActivator.handler")); MessagingAnnotationPostProcessor mapp = new MessagingAnnotationPostProcessor(); mapp.setBeanFactory(beanFactory); mapp.afterPropertiesSet(); mapp.postProcessAfterInitialization(new Foo(), "foo"); verify(beanFactory).registerSingleton(eq("channel"), any(DirectChannel.class)); }
@Test public void shouldDecorateCallableAndReturnWithSuccess() throws Throwable { // Given Bulkhead bulkhead = Bulkhead.of("test", config); BDDMockito.given(helloWorldService.returnHelloWorldWithException()).willReturn("Hello world"); // When Callable<String> callable = Bulkhead.decorateCallable(bulkhead, helloWorldService::returnHelloWorldWithException); // Then assertThat(callable.call()).isEqualTo("Hello world"); assertThat(bulkhead.getMetrics().getAvailableConcurrentCalls()).isEqualTo(1); BDDMockito.then(helloWorldService).should(times(1)).returnHelloWorldWithException(); }