@Test @DirtiesContext public void testNoDataFlowServer() throws Exception{ String exceptionMessage = null; final String ERROR_MESSAGE = "I/O error on GET request for \"http://localhost:9393\": Connection refused; nested exception is java.net.ConnectException: Connection refused"; Mockito.doThrow(new ResourceAccessException(ERROR_MESSAGE)) .when(this.taskOperations).launch(Matchers.anyString(), (Map<String,String>) Matchers.any(), (List<String>) Matchers.any()); TaskLauncherTasklet taskLauncherTasklet = getTaskExecutionTasklet(); ChunkContext chunkContext = chunkContext(); try { taskLauncherTasklet.execute(null, chunkContext); } catch (ResourceAccessException rae) { exceptionMessage = rae.getMessage(); } assertEquals(ERROR_MESSAGE, exceptionMessage); }
@Test(groups = "SearchFiles.getNextResponse") public void getNextResponse_should_return_valid_response() { try { SearchFiles searchFiles = new SearchFiles(config, null, searchRequest); PowerMockito.when( HttpUtils.doGet(Mockito.anyString(), Matchers.<Map<String, String>> any())).thenReturn( TEST_RESPONSE); SearchFilesResponse response = searchFiles.getNextResponse(); SearchFilesTest.checkTestResponse(response); Assert.assertEquals(searchFiles.currentSearchPageIndex(), 0); } catch (StockException e) { Assert.fail("Didn't expect the StockException!", e); } }
@Test(groups = "SearchFiles.getNextResponse", expectedExceptions = { StockException.class }, expectedExceptionsMessageRegExp = "No more search results available!") public void getNextResponse_should_throw_exception_since_offset_exceed_result_count() throws StockException { searchRequest.getSearchParams().setOffset( TEST_NB_RESULTS - TEST_DEFAULT_LIMIT); SearchFiles searchFiles = new SearchFiles(config, null, searchRequest); PowerMockito.when( HttpUtils.doGet(Mockito.anyString(), Matchers.<Map<String, String>> any())).thenReturn( TEST_RESPONSE); searchFiles.getNextResponse(); // calling next again will exceed results count limit searchFiles.getNextResponse(); }
@Test(groups = "SearchFiles.getNextResponse", expectedExceptions = { StockException.class }, expectedExceptionsMessageRegExp = "No more search results available!") public void getNextResponse_should_throw_exception_when_result_count_zero() throws StockException, IOException { String responseString = "{\"nb_results\":0,\"files\":[] }"; PowerMockito.mockStatic(DownSampleUtil.class); searchRequest.getSearchParams().setSimilarImage(true); searchRequest.setLocale("en-US"); searchRequest.setSimilarImage(new byte[10]); SearchFiles searchFiles = new SearchFiles(config, "accessToken", searchRequest); PowerMockito.when( HttpUtils.doMultiPart(Mockito.anyString(), Mockito.any(byte[].class), Matchers.<Map<String, String>> any())).thenReturn( responseString); PowerMockito.when( DownSampleUtil.downSampleImageUtil( Mockito.any(byte[].class))).thenReturn( new byte[10]); searchFiles.getNextResponse(); searchFiles.getNextResponse(); }
@Test public void prefetchData_withoutTemplates_bug12479() { // given List<Product> products = new ArrayList<Product>(); products.add(product); products.add(customerProduct); LocalizerFacade facadeMock = spy(facade); // when ProductAssembler.prefetchData(products, facadeMock, PerformanceHint.ONLY_FIELDS_FOR_LISTINGS); // then verify(facadeMock, times(1)).prefetch(objectKeyCaptor.capture(), Matchers.anyListOf(LocalizedObjectTypes.class)); List<Long> objectkeys = objectKeyCaptor.getValue(); assertEquals(2, objectkeys.size()); assertEquals(Long.valueOf(product.getKey()), objectkeys.get(0)); assertEquals(Long.valueOf(customerProduct.getKey()), objectkeys.get(1)); }
@Test public void getServicePort() throws MalformedURLException { // given Map<String, Setting> settings = getSettingsForMode("SAML_SP"); IdentityService idSvcMock = Mockito.mock(IdentityService.class); Service serviceMock = Mockito.mock(Service.class); doReturn(serviceMock).when(besDAO).createWebService(any(URL.class), any(QName.class)); when( serviceMock.getPort(Matchers.any(QName.class), eq(IdentityService.class))).thenReturn(idSvcMock); // when IdentityService idSvc = besDAO.getServicePort(IdentityService.class, settings); // then assertTrue(IdentityService.class.isAssignableFrom(idSvc.getClass())); }
@Test public void saveLangauges() throws Exception { // given List<POSupportedLanguage> poList = new ArrayList<POSupportedLanguage>(); poList.add(getPOSupportedLanguage(1, "en", true, true)); poList.add(getPOSupportedLanguage(2, "de", true, false)); poList.add(getPOSupportedLanguage(3, "ja", true, false)); poList.add(getPOSupportedLanguage(4, "te", false, false)); doNothing().when(operatorServiceLocal).saveLanguages( Matchers.anyListOf(SupportedLanguage.class)); // when service.saveLanguages(poList); // then verify(service.operatorService, times(1)).saveLanguages( Matchers.anyListOf(SupportedLanguage.class)); }
@Test public void delete_SubscriptionsChargeableActive_TechnicalServiceNotAliveException() throws Exception { Set<Subscription> subs = createSubs(SubscriptionStatus.ACTIVE); Subscription sub = subs.iterator().next(); sub.getPriceModel().setType(PriceModelType.PRO_RATA); // ensure that exception is not thrown Mockito.doThrow(new TechnicalServiceNotAliveException()) .when(applicationServiceMock) .deactivateInstance(Matchers.eq(sub)); paymentInfo.setSubscriptions(subs); accountServiceBean.deletePaymentInfo(pi); // verify that setRollbackOnly has been called never Mockito.verify(sessionContextMock, Mockito.never()).setRollbackOnly(); Assert.assertNull(sub.getPaymentInfo()); Assert.assertEquals(SubscriptionStatus.SUSPENDED, sub.getStatus()); Mockito.verify(paymentServiceMock, Mockito.times(1)) .deregisterPaymentInPSPSystem(Matchers.eq(paymentInfo)); Mockito.verify(applicationServiceMock, Mockito.times(1)) .deactivateInstance(Matchers.eq(sub)); }
@Test public void shouldTestInitNoConfiguration() { // given Element element = mock(Element.class); MediaWrapper<MediaBase> mediaDescriptor = mock(MediaWrapper.class); when(mediaDescriptor.getMediaObject()).thenReturn(mediaBase); when(mediaBase.getElement()).thenReturn(element); instance.setMediaWrapper(mediaDescriptor); mediaConfiguration = new BaseMediaConfiguration(new HashMap<String, String>(), false); instance.setBaseMediaConfiguration(mediaConfiguration); // when instance.init(); // then verify(mediaBase).setPreload(Matchers.eq(getAssumedMediaPreloadType())); verify(mediaBase).setControls(Matchers.eq(true)); for (Map.Entry<HTML5MediaEventsType, MediaEventTypes> typePair : createEventsPairMap().entrySet()) { verify(html5MediaNativeListeners).addListener(element, typePair.getKey().toString()); } }
@Test public void shouldInitiateValues_whenMediaBaseIsSet() { // given Element element = mock(Element.class); MediaWrapper<MediaBase> mediaDescriptor = mock(MediaWrapper.class); when(mediaDescriptor.getMediaObject()).thenReturn(mediaBase); when(mediaBase.getElement()).thenReturn(element); instance.setMediaWrapper(mediaDescriptor); instance.setBaseMediaConfiguration(mediaConfiguration); // when instance.init(); // then verify(mediaBase).setPreload(Matchers.eq(getAssumedMediaPreloadType())); verify(mediaBase).setControls(Matchers.eq(false)); for (Map.Entry<HTML5MediaEventsType, MediaEventTypes> typePair : createEventsPairMap().entrySet()) { verify(html5MediaNativeListeners).addListener(element, typePair.getKey().toString()); } }
@Test public void testAuthenticateLoginMissingHeader() throws Exception { Mockito.when(session.getAttribute(Matchers.eq("loggedInUserId"))) .thenReturn(null); Mockito.when(req.getHeader(Matchers.eq("Authorization"))) .thenReturn(null); // And go! filter.doFilter(req, resp, chain); // Check whether user will be asked for login Mockito.verify(resp).setStatus(Matchers.eq(401)); Mockito.verify(resp).setHeader(Matchers.eq("WWW-Authenticate"), Matchers.startsWith("Basic ")); }
@Test public void dragEndHandlerTest() { DragEndHandler endHandler = mock(DragEndHandler.class); ArgumentCaptor<DragEndEventWrapper> captor = ArgumentCaptor.forClass(DragEndEventWrapper.class); when(draggableWidget.addDragStopHandler(Matchers.any(DragStopEventHandler.class))).then(new Answer<HandlerRegistration>() { @Override public HandlerRegistration answer(InvocationOnMock invocation) throws Throwable { stopHandler = (DragStopEventHandler) invocation.getArguments()[0]; return null; } }); doNothing().when(instance).setData(Matchers.anyString(), Matchers.anyString()); doReturn(null).when(instance).getData(Matchers.anyString()); instance.wrap(endHandler); stopHandler.onDragStop(mock(DragStopEvent.class)); verify(endHandler).onDragEnd(captor.capture()); DragEndEventWrapper event = captor.getValue(); event.setData("text", "text"); event.getData("text"); verify(instance).setData(Matchers.eq("text"), Matchers.eq("text")); verify(instance).getData(Matchers.eq("text")); }
/** Drag together two incompatible blocks. */ @Test public void testDragNoConnect() throws BlockLoadingException { // Setup mTouchedBlock = mDraggedBlock = mBlockFactory.obtainBlockFrom( new BlockTemplate().ofType("simple_input_output")); mTargetBlock = mBlockFactory.obtainBlockFrom(new BlockTemplate().ofType("output_no_input")); Mockito.when(mMockBlockClipDataHelper.isBlockData(any(ClipDescription.class))) .thenReturn(true); Mockito.when(mMockConnectionManager.findBestConnection(any(Block.class), anyInt())) .thenReturn(null); setupDrag(); dragBlockToTarget(); Mockito.verify(mMockConnectionManager, atLeastOnce()) .findBestConnection(Matchers.same(mTouchedBlock), anyInt()); Mockito.verify(mMockController, never()) .connect(any(Connection.class), any(Connection.class)); }
@Test public void prefetchData_withTemplates_bug12479() { // given List<Product> products = new ArrayList<Product>(); products.add(product); Product anotherProduct = new Product(); anotherProduct.setType(ServiceType.PARTNER_TEMPLATE); anotherProduct.setConfiguratorUrl("some value"); anotherProduct.setTemplate(template); products.add(anotherProduct); products.add(customerProduct); LocalizerFacade facadeMock = spy(facade); // when ProductAssembler.prefetchData(products, facadeMock, PerformanceHint.ONLY_FIELDS_FOR_LISTINGS); // then verify(facadeMock, times(1)).prefetch(objectKeyCaptor.capture(), Matchers.anyListOf(LocalizedObjectTypes.class)); List<Long> objectkeys = objectKeyCaptor.getValue(); assertEquals(3, objectkeys.size()); assertEquals(Long.valueOf(product.getKey()), objectkeys.get(0)); assertEquals(Long.valueOf(template.getKey()), objectkeys.get(1)); assertEquals(Long.valueOf(customerProduct.getKey()), objectkeys.get(2)); }
@Test(groups = "LicenseHistory.getPreviousLicenseHistory") public void getPreviousLicenseHistory_should_return_valid_response() { try { licenseHistoryRequest.getSearchParams().setOffset(TEST_DEFAULT_LIMIT); LicenseHistory licenseHistory = new LicenseHistory(config, null, licenseHistoryRequest); PowerMockito.when( HttpUtils.doGet(Mockito.anyString(), Matchers.<Map<String, String>> any())).thenReturn( TEST_RESPONSE); LicenseHistoryResponse response = licenseHistory.getPreviousLicenseHistory(); LicenseHistoryTest.checkTestResponse(response); Assert.assertEquals(licenseHistory.currentLicenseHistoryPageIndex(), 0); } catch (StockException e) { Assert.fail("Didn't expect the StockException!", e); } }
@Test public void testGetConfiguration_MarketplaceNotFound() throws Exception { // Mock logging Log4jLogger loggerMock = mock(Log4jLogger.class); when(beanSpy.getLogger()).thenReturn(loggerMock); final String marketplaceId = "notFound"; when(msMock.getMarketplaceById(Matchers.anyString())).thenThrow( new ObjectNotFoundException()); // Simulate accessing none existing marketplace MarketplaceConfiguration mpc = beanSpy.getConfiguration(marketplaceId); // Ensure error is logged... verify(loggerMock, times(1)).logError( Matchers.eq(Log4jLogger.SYSTEM_LOG), Matchers.any(ObjectNotFoundException.class), Matchers.eq(LogMessageIdentifier.ERROR_MARKETPLACE_NOT_FOUND), Matchers.eq(marketplaceId)); // and default configuration is returned Assert.assertNull(mpc); }
@Test public void getMessages_should_request_message_search() throws MessagingException { int totalMessages = 23; int messageStart = 1; int messageEnd = 11; setupFolderWithMessages(totalMessages); String messagesXml = "<xml>MessagesXml</xml>"; buildSearchResponse(mockDataSet); when(mockStore.getMessagesXml()).thenReturn(messagesXml); when(mockStore.processRequest(eq("https://localhost/webDavStoreUrl/testFolder"), eq("SEARCH"), eq(messagesXml), Matchers.<Map<String, String>>any())).thenReturn(mockDataSet); folder.getMessages(messageStart, messageEnd, new Date(), listener); verify(listener, times(5)).messageStarted(anyString(), anyInt(), eq(5)); verify(listener, times(5)).messageFinished(any(WebDavMessage.class), anyInt(), eq(5)); }
@Test public void doFilter_accessLocalMPinAdministrationPortalContext() throws Exception { // accessing a global MP in the MPL brand is fine, NO redirect final String mId = "fdfb4933"; fakeRequest(mId, null); fakeCreateMarketplace(mId); mpCtxFilter.doFilter(requestMock, responseMock, chainMock); // MPL portal request and trying to access global MP, thus no redirect verify(responseMock, never()).sendRedirect( Matchers.contains(Marketplace.PUBLIC_CATALOG_SITE)); // if mId given, do not use fallback via subscription key or cookie verify(mpSvcMock, never()).getMarketplaceForSubscription( Matchers.anyLong(), Matchers.anyString()); verify(requestMock, times(1)).getCookies(); assertEquals(mId, sessionMid); }
@Test public void testAuthenticateWithException() throws Exception { exception = true; platformService.exceptionOnGetControllerSettings = new APPlatformException( "failed"); Mockito.when(session.getAttribute(Matchers.eq("loggedInUserId"))) .thenReturn(null); String credentials = "user1:password1"; String credentialsEncoded = Base64 .encodeBase64String(credentials.getBytes()); Mockito.when(req.getHeader(Matchers.eq("Authorization"))) .thenReturn("Basic " + credentialsEncoded); // And go! filter.doFilter(req, resp, chain); // Check whether request has been forwarded Mockito.verify(resp).setStatus(Matchers.eq(401)); Mockito.verify(resp).setHeader(Matchers.eq("WWW-Authenticate"), Matchers.startsWith("Basic ")); }
@Test public void doFilter_MpRedirect() throws Exception { when(requestMock.getServletPath()).thenReturn( BaseBean.MARKETPLACE_REDIRECT); mpCtxFilter.doFilter(requestMock, responseMock, chainMock); // MPL portal request, thus no redirect required verify(responseMock, times(1)).sendRedirect( Matchers.contains(Marketplace.MARKETPLACE_ROOT)); // if mId given, do not use fallback via subscription key or cookie verify(mpSvcMock, never()).getMarketplaceForSubscription( Matchers.anyLong(), Matchers.anyString()); verify(requestMock, times(1)).getCookies(); verify(sessionMock, never()).setAttribute( Constants.REQ_PARAM_MARKETPLACE_ID, Any.class); }
@Test public void testReadWriteOperations() throws Exception { doReturn(Futures.immediateCheckedFuture(Optional.absent())).when(readTx) .read(any(), any()); rwTx.put(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH, testNodeWithOuter(1, 2, 3)); verify(writeTx).put(eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(TestModel.TEST_PATH), Matchers.eq(testNodeWithOuter(1, 2, 3))); verify(readTx).read(eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(TestModel.TEST_PATH)); assertEquals(testNodeWithOuter(1, 2, 3), rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet().get()); rwTx.merge(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH, testNodeWithOuter(4, 5, 6)); assertEquals(testNodeWithOuter(1, 2, 3, 4, 5, 6), rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet().get()); rwTx.delete(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH); verify(writeTx).delete(eq(LogicalDatastoreType.OPERATIONAL), Matchers.eq(TestModel.TEST_PATH)); assertEquals(Optional.absent(), rwTx.read(LogicalDatastoreType.OPERATIONAL, TestModel.TEST_PATH).checkedGet()); }
@Before public void setup() throws IOException { PowerMockito.mockStatic(FileSystem.class); when(context.getConfiguration()).thenReturn(configuration); when(configuration.get(Matchers.anyString())).thenReturn("0"); when(context.getInputSplit()).thenReturn(fileSplit); final Path path = new Path("/source/path/"); when(fileSplit.getPath()).thenReturn(path); when(FileSystem.get(any(URI.class), any(Configuration.class))).thenReturn(fileSystem); FileStatus[] fileStatuses = {fileStatus}; when(fileSystem.listStatus(any(Path.class))).thenReturn(fileStatuses); when(fileStatus.isDirectory()).thenReturn(false); when(fileStatus.getLen()).thenReturn(1234L); when(fileStatus.getPath()).thenReturn(path); }
@Test public void savePaymentInfo_TypeChangeSupportedWithDeregistration() throws Exception { // change from credit card to direct debit setReferenceByBusinessKeyResult(invoice); enablePaymentType(invoice); Set<Subscription> subs = createSubs(SubscriptionStatus.ACTIVE, invoice); Subscription sub = subs.iterator().next(); sub.getPriceModel().setType(PriceModelType.PRO_RATA); accountServiceBean.savePaymentInfo(pi); // service instance must not be deactivated Mockito.verifyNoMoreInteractions(applicationServiceMock); // payment has to be deregistered Mockito.verify(paymentServiceMock, Mockito.times(1)) .deregisterPaymentInPSPSystem(Matchers.eq(paymentInfo)); Mockito.verify(dataServiceMock, Mockito.times(1)).flush(); Assert.assertEquals(SubscriptionStatus.ACTIVE, sub.getStatus()); Assert.assertEquals(invoice, paymentInfo.getPaymentType()); Assert.assertNull(paymentInfo.getExternalIdentifier()); }
@Test public void doFilter_redirectToMPErrorPage() throws Exception { // given String mpRedirect = "http://thisisaurl/xxxx" + BaseBean.MARKETPLACE_START_SITE; when(requestMock.getServletPath()).thenReturn( BaseBean.MARKETPLACE_START_SITE); when(requestMock.getRequestURI()).thenReturn( "xxxx" + BaseBean.MARKETPLACE_START_SITE); doReturn(mpRedirect).when(mpCtxFilter).getRedirectMpUrlHttp( any(ConfigurationService.class)); // when mpCtxFilter.doFilter(requestMock, responseMock, chainMock); // then verify(mpCtxFilter, times(1)).sendRedirect( any(HttpServletRequest.class), Matchers.eq(responseMock), anyString()); }
/** Drag together two compatible blocks. */ @Test public void testDragConnect() throws BlockLoadingException { // Setup mTouchedBlock = mDraggedBlock = mBlockFactory.obtainBlockFrom( new BlockTemplate().ofType("simple_input_output")); mTargetBlock = mBlockFactory.obtainBlockFrom(new BlockTemplate().ofType("output_no_input")); Mockito.when(mMockBlockClipDataHelper.isBlockData(any(ClipDescription.class))) .thenReturn(true); Mockito.when( mMockConnectionManager.findBestConnection(Matchers.same(mTouchedBlock), anyInt())) .thenReturn(Pair.create(mTouchedBlock.getOnlyValueInput().getConnection(), mTargetBlock.getOutputConnection())); setupDrag(); dragBlockToTarget(); Mockito.verify(mMockConnectionManager, atLeastOnce()) .findBestConnection(Matchers.same(mTouchedBlock), anyInt()); Mockito.verify(mMockController).connect( mTouchedBlock.getOnlyValueInput().getConnection(), mTargetBlock.getOutputConnection()); }
@SuppressWarnings("unchecked") @Test(expected = AuthenticationException.class) public void testAuthenticateTMForInstance_noRoles() throws Throwable { // given createServiceInstance(ProvisioningStatus.COMPLETED, InstanceParameter.PUBLIC_IP); VOUserDetails user = createVOUserDetails(10000, "supplier", "tp123"); Mockito.doReturn(user).when(besDAO).getUserDetails( any(ServiceInstance.class), any(VOUser.class), anyString(), any(Optional.class)); Mockito.doReturn(new PasswordAuthentication("nobody", "")) .when(configService).getWebServiceAuthentication( any(ServiceInstance.class), Matchers.anyMap(), any(Optional.class)); // when authenticateTMForInstance(CTRL_ID, "appInstanceId", new PasswordAuthentication("supplier", "secret")); }
@Before public void setUp() throws Exception { // Intercept when startForwarding is called leader = mock(Leader.class); when( leader.startForwarding(Matchers.any(LearnerHandler.class), Matchers.anyLong())).thenAnswer(new Answer() { public Object answer(InvocationOnMock invocation) { currentZxid = (Long) invocation.getArguments()[1]; return 0; } }); sock = mock(Socket.class); db = new MockZKDatabase(null); learnerHandler = new MockLearnerHandler(sock, leader); }
@Before public void setup() throws Exception { sqlConn = Mockito.mock(Connection.class); statement = Mockito.mock(PreparedStatement.class); resultSet = Mockito.mock(ResultSet.class); sqlStatementes = new ArrayList<>(); prepStatements = new Stack<>(); Mockito.when(sqlConn.prepareStatement(Matchers.anyString())) .thenReturn(statement); Mockito.when(statement.executeQuery()).thenReturn(resultSet); p_driverClass = "java.lang.String"; tempFile = File.createTempFile("temp", ".properties"); tempFile.deleteOnExit(); p_propertyFile = tempFile.getAbsolutePath(); }
@Test public void doFilter_redirectToConfiguredMPErrorRedirectPage() throws Exception { // given String mpRedirect = "http://thisisaurl/xxxx/marketplace/?mId=aaa"; when(requestMock.getServletPath()).thenReturn( BaseBean.MARKETPLACE_START_SITE); when(requestMock.getRequestURI()).thenReturn( "xxxx" + BaseBean.MARKETPLACE_START_SITE); doReturn(mpRedirect).when(mpCtxFilter).getRedirectMpUrlHttp( any(ConfigurationService.class)); // when mpCtxFilter.doFilter(requestMock, responseMock, chainMock); // then verify(responseMock, times(1)).sendRedirect(Matchers.eq(mpRedirect)); verify(sessionMock, never()).invalidate(); verify(mpCtxFilter, never()).forward(any(String.class), any(HttpServletRequest.class), Matchers.eq(responseMock)); }
@Test public void testLockServiceInstance() throws Exception { // given Mockito.when(new Boolean(concSvc.lockServiceInstance( Matchers.matches("ctrl.id"), Matchers.matches("inst.id")))) .thenReturn(Boolean.TRUE); // then assertTrue(platformSvc.lockServiceInstance("ctrl.id", "inst.id", defaultAuth)); Mockito.verify(concSvc, Mockito.times(1)).lockServiceInstance( Matchers.eq("ctrl.id"), Matchers.eq("inst.id")); Mockito.verify(authSvc, Mockito.times(1)).authenticateTMForInstance( Matchers.anyString(), Matchers.anyString(), Matchers.any(PasswordAuthentication.class)); }
@Test public void testAuthenticateLoggedIn() throws Exception { Mockito.when(session.getAttribute(Matchers.eq("loggedInUserId"))) .thenReturn("user1"); // And go! filter.doFilter(req, resp, chain); // Check whether request has been forwarded Mockito.verify(chain).doFilter(Matchers.eq(req), Matchers.eq(resp)); }
@SuppressWarnings("unchecked") @Test public void testAuthenticateTMForController_controllerSettingsMatch() throws Throwable { // given Map<String, String> proxySettings = getProxySettingsForMode("INTERNAL"); Map<String, Setting> controlleSettings = getControllerSettingsForOrg( "tp123"); Mockito.doReturn(proxySettings).when(configService) .getAllProxyConfigurationSettings(); Mockito.doReturn(controlleSettings).when(configService) .getControllerConfigurationSettings(anyString()); Mockito.doReturn(new PasswordAuthentication("user", "pass")) .when(configService) .getAuthenticationForBESTechnologyManager(anyString(), any(ServiceInstance.class), Matchers.anyMap()); Mockito.doReturn(null).when(authService) .getAuthenticatedTMForController(anyString(), any(PasswordAuthentication.class)); // when authenticateTMForController(CTRL_ID, "user", "pass"); // then verify(authService, Mockito.times(0)) .getAuthenticatedTMForController(anyString(), any(PasswordAuthentication.class)); }
@Test public void detectAndCreateShimOutViewsNullShimOutViewListTest() { mPopUpCoachMarkPresenter.detectAndCreateShimOutViews(null); Mockito.verify(mPopUpCoachMarkPresentation, Mockito.times(0)). createViewToBeMaskedOut(Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt(), Matchers.anyInt()); Mockito.verifyNoMoreInteractions(mPopUpCoachMarkPresentation); }
@Test public void testRegisterCustomerForSupplierLdap() throws Exception { container.login(String.valueOf(supplier1User.getKey()), ROLE_SERVICE_MANAGER); LdapProperties props = prepareLdapProperties(null); final VOOrganization customer = registerCustomerForSupplierLdap(props, null, null); Assert.assertNotNull(customer); verify(ldapSettingMmgtMock, times(1)).setOrganizationSettings( Matchers.anyString(), Matchers.any(Properties.class)); assertEquals(props.asProperties(), storedProps.getValue()); verify(ldapSettingMmgtMock, times(1)) .getOrganizationSettingsResolved(Matchers.anyString()); }
@Test public void shouldSendEidasRequestToMatchingServiceViaAttributeQueryServiceAndUpdateSessionStateWhenSuccessfulResponseIsReceived() { final EidasAttributeQueryRequestDto eidasAttributeQueryRequestDto = EidasAttributeQueryRequestDtoBuilder.anEidasAttributeQueryRequestDto().build(); final Cycle3AttributeRequestData attributeRequestData = new Cycle3AttributeRequestData("attribute-name", "issuer-id"); final SessionId eidasSessionId = SessionIdBuilder.aSessionId().build(); when(eidasAwaitingCycle3DataStateController.getCycle3AttributeRequestData()).thenReturn(attributeRequestData); when(sessionRepository.getStateController(eidasSessionId, AbstractAwaitingCycle3DataState.class)).thenReturn(eidasAwaitingCycle3DataStateController); when(eidasAwaitingCycle3DataStateController.createAttributeQuery(Matchers.any(Cycle3Dataset.class))).thenReturn(eidasAttributeQueryRequestDto); service.sendCycle3MatchingRequest(eidasSessionId, cycle3UserInput); verify(eidasAwaitingCycle3DataStateController).createAttributeQuery(Matchers.any(Cycle3Dataset.class)); verify(attributeQueryService).sendAttributeQueryRequest(eidasSessionId, eidasAttributeQueryRequestDto); verify(eidasAwaitingCycle3DataStateController).handleCycle3DataSubmitted("principal-ip-address-as-seen-by-hub"); }
@Before public void setupTest() { MockitoAnnotations.initMocks(TagBookmarkPresenterTest.this); List<Tag> tags = new ArrayList<>(); tags.add(new Tag(1, "Test")); when(bookmarkModel.tagsObservable()).thenReturn(Observable.empty()); when(bookmarkModel.getTagsObservable()).thenReturn(Single.just(tags)); when(bookmarkModel.getBookmarkTagIds(Matchers.any())) .thenReturn(Maybe.empty()); }
@Before public void init() { doReturn(firstCopier).when(firstCopierFactory).newInstance(anyString(), any(Path.class), Matchers.<List<Path>> any(), any(Path.class), Matchers.<Map<String, Object>> any()); doReturn(firstCopier).when(firstCopierFactory).newInstance(anyString(), any(Path.class), any(Path.class), Matchers.<Map<String, Object>> any()); doReturn(secondCopier).when(secondCopierFactory).newInstance(anyString(), any(Path.class), Matchers.<List<Path>> any(), any(Path.class), Matchers.<Map<String, Object>> any()); doReturn(secondCopier).when(secondCopierFactory).newInstance(anyString(), any(Path.class), any(Path.class), Matchers.<Map<String, Object>> any()); }
@Test public void removeMarketingPermission_GoodCase() throws Exception { container.login(1, ROLE_TECHNOLOGY_MANAGER); accountMgmt.removeSuppliersFromTechnicalService( new VOTechnicalService(), new ArrayList<String>()); verify(marketingPermissionMock, times(1)).removeMarketingPermission( Matchers.anyLong(), Matchers.anyListOf(String.class)); }
@Test public void mediaEventTextTrackUpdateTestWithoutTextTrack() { // prepare mediaWrapper = Mockito.mock(MediaWrapper.class); VideoTextTrackElement instance = Mockito.spy(trackElementFactory.getVideoTextTrackElement(TextTrackKind.CAPTIONS)); instance.setMediaDescriptor(mediaWrapper); instance.init(); MediaEvent event = new MediaEvent(MediaEventTypes.TEXT_TRACK_UPDATE); // test eventsBus.fireEventFromSource(event, mediaWrapper, pageScopeFactory.getCurrentPageScope()); verify(instance).onMediaEvent(eq(event)); verify(instance, Mockito.times(0)).showHideText(Matchers.any(TextTrackCue.class)); }