@Test public void ensurePersonCanBeCreatedWithOnlyLoginName() { Person person = TestDataCreator.createPerson(); Mockito.when( personService.create( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyListOf(MailNotification.class), Mockito.anyListOf(Role.class))) .thenReturn(person); ldapSyncService.createPerson("murygina", Optional.empty(), Optional.empty(), Optional.empty()); Mockito.verify(personService) .create( "murygina", null, null, null, Collections.singletonList(MailNotification.NOTIFICATION_USER), Collections.singletonList(Role.USER)); }
@Test public void ensurePersonIsCreatedWithCorrectAttributes() { Person person = TestDataCreator.createPerson(); Mockito.when( personService.create( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyListOf(MailNotification.class), Mockito.anyListOf(Role.class))) .thenReturn(person); ldapSyncService.createPerson( "murygina", Optional.of("Aljona"), Optional.of("Murygina"), Optional.of("*****@*****.**")); Mockito.verify(personService) .create( "murygina", "Murygina", "Aljona", "*****@*****.**", Collections.singletonList(MailNotification.NOTIFICATION_USER), Collections.singletonList(Role.USER)); }
@Test public void testCreateSuccess() { RegionService regionService = Mockito.mock(RegionService.class); Region region = Mockito.mock(Region.class); Mockito.when( regionService.addRegion( Mockito.anyInt(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString())) .thenReturn(region); addRegionCmd._regionService = regionService; responseGenerator = Mockito.mock(ResponseGenerator.class); RegionResponse regionResponse = Mockito.mock(RegionResponse.class); Mockito.when(responseGenerator.createRegionResponse(region)).thenReturn(regionResponse); addRegionCmd._responseGenerator = responseGenerator; addRegionCmd.execute(); }
@Test public final void shouldSaveAndSetOwnerEntity() { // given given(owner.isValid()).willReturn(true); given(savedOwner.isValid()).willReturn(true); given(ownerDD.save(owner)).willReturn(savedOwner); // when stateChangeContext.setOwner(owner); // then verify(ownerDD).save(owner); verify(stateChangeEntity, never()).setField(describer.getOwnerFieldName(), owner); verify(stateChangeEntity).setField(describer.getOwnerFieldName(), savedOwner); verify(messageService, never()) .addValidationError( Mockito.eq(stateChangeContext), Mockito.anyString(), Mockito.anyString(), Mockito.any(String[].class)); verify(messageService, never()) .addValidationError( Mockito.eq(stateChangeContext), Mockito.eq((String) null), Mockito.anyString(), Mockito.any(String[].class)); verify(stateChangeEntity, never()) .setField(describer.getStatusFieldName(), StateChangeStatus.FAILURE.getStringValue()); }
@Test public void shouldAllowPeriodicFeeForNonVariableInstallmentLoanProduct() { String PERIODIC_FEE_2 = "2"; String NON_PERIODIC_FEE = "3"; final FeeDto feeDto = Mockito.mock(FeeDto.class); loanPrdActionForm = new LoanPrdActionForm() { @Override FeeDto getFeeDto( @SuppressWarnings("unused") HttpServletRequest request, @SuppressWarnings("unused") FeeBO fee) { return feeDto; } }; FeeFrequencyEntity feeFrequencyEntity = Mockito.mock(FeeFrequencyEntity.class); MeetingBO meetingBo = Mockito.mock(MeetingBO.class); MeetingDetailsEntity meetingDetailsEntity = Mockito.mock(MeetingDetailsEntity.class); when(periodicFeeRate.isPeriodic()).thenReturn(true); when(periodicFeeRate.getFeeType()).thenReturn(RateAmountFlag.RATE); when(periodicFeeRate.getFeeId()).thenReturn(Short.valueOf(PERIODIC_FEE_2)); when(periodicFeeRate.getFeeName()).thenReturn("periodic fee2"); when((periodicFeeRate).getFeeFormula()).thenReturn(feeFormulaEntity); when(feeFormulaEntity.getFeeFormula()).thenReturn(FeeFormula.INTEREST); when(periodicFeeRate.getFeeFrequency()).thenReturn(feeFrequencyEntity); when(nonPeriodicFeeRate.isPeriodic()).thenReturn(false); when(nonPeriodicFeeRate.getFeeType()).thenReturn(RateAmountFlag.RATE); when(nonPeriodicFeeRate.getFeeId()).thenReturn(Short.valueOf(NON_PERIODIC_FEE)); when(nonPeriodicFeeRate.getFeeName()).thenReturn("non Periodic fee"); when(((RateFeeBO) nonPeriodicFeeRate).getFeeFormula()).thenReturn(feeFormulaEntity); when(feeFormulaEntity.getFeeFormula()).thenReturn(FeeFormula.INTEREST); List<FeeBO> allPrdFees = new ArrayList<FeeBO>(); allPrdFees.add(periodicFeeRate); allPrdFees.add(nonPeriodicFeeRate); when(request.getAttribute(Constants.CURRENTFLOWKEY)).thenReturn(FLOW_KEY); when(request.getSession()).thenReturn(session); when(session.getAttribute(Constants.FLOWMANAGER)).thenReturn(flowManager); when(session.getAttribute(ProductDefinitionConstants.LOANPRDFEE)).thenReturn(allPrdFees); Flow flow = new Flow(); try { when(flowManager.getFromFlow(Mockito.anyString(), Mockito.anyString())) .thenReturn(allPrdFees); when(flowManager.getFlowWithValidation(FLOW_KEY)).thenReturn(flow); } catch (PageExpiredException e) { // TODO Auto-generated catch block e.printStackTrace(); } loanPrdActionForm.setCanConfigureVariableInstallments(false); loanPrdActionForm.setPrdOfferinFees(new String[] {PERIODIC_FEE_2, NON_PERIODIC_FEE}); loanPrdActionForm.validateSelectedFeeForVariableInstallment(request, errors); Mockito.verifyZeroInteractions(errors); }
@Test public void getBluetoothActiveDuration() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { // delta +delta (sum) "1.413913535177E9 CONNECTED" // 1413913591.806 - 1413913535.177 = 56.629 56.629 , "1.413913591806E9 CONNECTED" // 1413913610.613 - 1413913591.806 = 18.807 75.436 , "1.413913610613E9 OFF" // 1413913620.683 - 1413913610.613 = 10.070 , "1.413913620683E9 DISCONNECTED" // 1413913620.883 - 1413913620.683 = 0.200 , "1.413913620883E9 CONNECTED" // 1413913622.533 - 1413913620.883 = 1.650 77.086 , "1.413913622533E9 JUNK" // 1413913622.533 , "" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); double activeDuration = bluetoothReader.getBluetoothActiveDuration(); assertEquals(77.086, ((double) Math.round(activeDuration * 1000.0)) / 1000, 0); // bcn faked // assertEquals(77.086, activeDuration, 0); }
@Before public void setUp() throws Exception { Context.set(Context.standaloneContext()); MockitoAnnotations.initMocks(this); when(mockUriLocatorFactory.getInstance(Mockito.anyString())).thenReturn(mockUriLocator); when(mockUriLocator.locate(Mockito.anyString())).thenReturn(WroUtil.EMPTY_STREAM); when(mockUriLocatorFactory.locate(Mockito.anyString())).thenReturn(WroUtil.EMPTY_STREAM); when(mockRequest.getAttribute(Mockito.anyString())).thenReturn(null); when(mockManagerFactory.create()).thenReturn(new BaseWroManagerFactory().create()); when(mockFilterConfig.getServletContext()).thenReturn(mockServletContext); when(mockResponse.getOutputStream()) .thenReturn(new DelegatingServletOutputStream(new ByteArrayOutputStream())); victim = new WroFilter() { @Override protected void onRuntimeException( final RuntimeException e, final HttpServletResponse response, final FilterChain chain) { throw e; } }; victim.setWroManagerFactory(mockManagerFactory); // victim.init(mockFilterConfig); }
@Test public void readData1() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); String[] arr = new String[] { // delta +delta (sum) "1.413913535177E9 CONNECTED" // 1413913591.806 - 1413913535.177 = 56.629 56.629 , "1.413913591806E9 CONNECTED" // 1413913610.613 - 1413913591.806 = 18.807 75.436 , "1.413913610613E9 OFF" // 1413913620.683 - 1413913610.613 = 10.070 , "1.413913620683E9 DISCONNECTED" // 1413913620.883 - 1413913620.683 = 0.200 , "1.413913620883E9 CONNECTED" // 1413913622.533 - 1413913620.883 = 1.650 77.086 , "1.413913622533E9 JUNK" // 1413913622.533 , "" }; Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(arr); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); assertEquals(1.413913622533E9, bluetoothInfo.get(5).getBeginTimeStamp(), 0); assertEquals(1.413913622533E9, bluetoothInfo.get(4).getEndTimeStamp(), 0); assertEquals(0, bluetoothInfo.get(5).getEndTimeStamp(), 0); assertEquals("BLUETOOTH_UNKNOWN", bluetoothInfo.get(5).getBluetoothState().toString()); assertEquals("BLUETOOTH_DISCONNECTED", bluetoothInfo.get(3).getBluetoothState().toString()); assertEquals("BLUETOOTH_CONNECTED", bluetoothInfo.get(1).getBluetoothState().toString()); assertEquals("BLUETOOTH_TURNED_OFF", bluetoothInfo.get(2).getBluetoothState().toString()); }
@Before public void setUp() { initMocks(this); map.clear(); when(mockServletContextEvent.getServletContext()).thenReturn(mockServletContext); when(mockServletContext.getAttribute(Mockito.anyString())) .then( new Answer<Object>() { public Object answer(final InvocationOnMock invocation) throws Throwable { return map.get((String) invocation.getArguments()[0]); } }); Mockito.doAnswer( new Answer<Object>() { public Object answer(final InvocationOnMock invocation) throws Throwable { final String key = (String) invocation.getArguments()[0]; final Object value = invocation.getArguments()[1]; return map.put(key, value); } }) .when(mockServletContext) .setAttribute(Mockito.anyString(), Mockito.anyObject()); Mockito.doAnswer( new Answer<Object>() { public Object answer(final InvocationOnMock invocation) throws Throwable { final Object value = invocation.getArguments()[0]; return map.remove(value); } }) .when(mockServletContext) .removeAttribute(Mockito.anyString()); victim = new WroServletContextListener(); }
/** * PDI-11363. when using getLookup calls there is no need to make attempt to retrieve row set * metadata for every call. That may bring performance penalty depends on jdbc driver * implementation. For some drivers that penalty can be huge (postgres). * * <p>During the execution calling getLookup() method we changing usually only lookup where clause * which will not impact return row structure. * * @throws KettleDatabaseException * @throws SQLException */ @Test public void testGetLookupMetaCalls() throws KettleDatabaseException, SQLException { DatabaseMeta meta = Mockito.mock(DatabaseMeta.class); Mockito.when(meta.getQuotedSchemaTableCombination(Mockito.anyString(), Mockito.anyString())) .thenReturn("a"); Mockito.when(meta.quoteField(Mockito.anyString())).thenReturn("a"); PreparedStatement ps = Mockito.mock(PreparedStatement.class); ResultSet rs = Mockito.mock(ResultSet.class); Mockito.when(ps.executeQuery()).thenReturn(rs); ResultSetMetaData rmeta = Mockito.mock(ResultSetMetaData.class); Mockito.when(rs.getMetaData()).thenReturn(rmeta); Mockito.when(rmeta.getColumnCount()).thenReturn(0); Mockito.when(ps.getMetaData()).thenReturn(rmeta); Database db = new Database(log, meta); Connection conn = Mockito.mock(Connection.class); Mockito.when(conn.prepareStatement(Mockito.anyString())).thenReturn(ps); db.setConnection(conn); String[] name = new String[] {"a"}; db.setLookup("a", name, name, name, name, "a"); for (int i = 0; i < 10; i++) { db.getLookup(); } Mockito.verify(rmeta, Mockito.times(1)).getColumnCount(); }
@Test public void testPassingInvalidAffiliationTypeSetsAffiliationToNone() throws Exception { IQ request = toIq( readStanzaAsString("/iq/pubsub/affiliation/affiliationChange.stanza") .replaceFirst("affiliation='member'", "affiliation='i-can-haz-all-the-items'")); NodeAffiliation affiliationActor = Mockito.mock(NodeAffiliation.class); Mockito.when(affiliationActor.getAffiliation()).thenReturn(Affiliations.moderator); ResultSet<NodeSubscription> subscriptions = new ResultSetImpl(new ArrayList<NodeSubscription>()); Mockito.when(channelManager.getNodeSubscriptionListeners(Mockito.anyString())) .thenReturn(subscriptions); Mockito.when(channelManager.nodeExists(node)).thenReturn(true); Mockito.when(channelManager.getUserAffiliation(Mockito.anyString(), Mockito.any(JID.class))) .thenReturn(affiliationActor); event.setChannelManager(channelManager); event.process(element, jid, request, null); Mockito.verify(channelManager) .setUserAffiliation( Mockito.anyString(), Mockito.any(JID.class), Mockito.eq(Affiliations.none)); }
@Test public void invalidBluetoothEntry1() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())) .thenReturn( new String [] { // delta +delta (sum) "1.413913535177E9 this is InVaLiD" // 1413913591.806 - 1413913535.177 = 56.629 // 56.629 , "1.413913591806E9 CONNECTED" // 1413913610.613 - 1413913591.806 = 18.807 75.436 , "1.413913610613E9 OFF" // 1413913620.683 - 1413913610.613 = 10.070 , "1.413913620683E9 DISCONNECTED" // 1413913620.883 - 1413913620.683 = 0.200 , "1.413913620883E9 CONNECTED" // 1413913622.533 - 1413913620.883 = 1.650 77.086 , "1.413913622533E9 CONNECTED" // 1413913622.533 , "" }); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); }
@Before public final void init() { workPlanService = new WorkPlansServiceImpl(); dataDefinitionService = mock(DataDefinitionService.class); TranslationService translationService = mock(TranslationService.class); workPlan = mock(Entity.class); workPlanDD = mock(DataDefinition.class); when(dataDefinitionService.get( WorkPlansConstants.PLUGIN_IDENTIFIER, WorkPlansConstants.MODEL_WORK_PLAN)) .thenReturn(workPlanDD); when(translationService.translate( Mockito.anyString(), Mockito.any(Locale.class), Mockito.anyString())) .thenReturn(TRANSLATED_STRING); when(workPlanDD.getName()).thenReturn(WorkPlansConstants.MODEL_WORK_PLAN); when(workPlanDD.getPluginIdentifier()).thenReturn(WorkPlansConstants.PLUGIN_IDENTIFIER); when(workPlanDD.get(Mockito.anyLong())).thenReturn(workPlan); when(workPlan.getDataDefinition()).thenReturn(workPlanDD); when(workPlan.getId()).thenReturn(1L); ReflectionTestUtils.setField(workPlanService, "dataDefinitionService", dataDefinitionService); ReflectionTestUtils.setField(workPlanService, "translationService", translationService); }
@Test public void testAddComment() throws Exception { prepare(GetMetaDataCommand.class, RefreshMetaDataCommand.class, AddCommentCommand.class); // create artifact and load into shell context using getMetaData pushToOutput("getMetaData --uuid %s", artifact.getUuid()); // setup Mockito.when( clientMock.addComment( Mockito.anyString(), Mockito.any(ArtifactType.class), Mockito.anyString())) .thenReturn(artifact); // add comment pushToOutput("addComment 'Comment Test'"); // add comment to mock Comment comment = new Comment(); comment.setText("Comment Test"); artifact.getComment().add(comment); // verify Mockito.verify(clientMock).addComment(artifact.getUuid(), artifactType, "Comment Test"); Assert.assertTrue(stream.toString().contains("Comment successfully created")); pushToOutput("refreshMetaData"); Assert.assertTrue(stream.toString().contains(": Comment Test")); }
@Test public void shouldValidateForGracePeriodWithDIPBInterestTypeAndVariableInstallments() { ActionMessageMatcher actionMessageMatcher = new ActionMessageMatcher( ProductDefinitionConstants.INVALID_INTEREST_TYPE_FOR_GRACE_PERIODS); loanPrdActionForm.setGracePeriodType(GraceType.PRINCIPALONLYGRACE.getValueAsString()); loanPrdActionForm.setCanConfigureVariableInstallments(true); loanPrdActionForm.setInterestTypes(InterestType.FLAT.getValueAsString()); loanPrdActionForm.validateInterestTypeForGracePeriods(errors, Locale.getDefault()); Mockito.verify(errors).add(Mockito.anyString(), Mockito.argThat(actionMessageMatcher)); Mockito.reset(errors); loanPrdActionForm.setGracePeriodType(GraceType.PRINCIPALONLYGRACE.getValueAsString()); loanPrdActionForm.setCanConfigureVariableInstallments(false); loanPrdActionForm.setInterestTypes(InterestType.DECLINING_PB.getValueAsString()); loanPrdActionForm.validateInterestTypeForGracePeriods(errors, Locale.getDefault()); Mockito.verify(errors).add(Mockito.anyString(), Mockito.argThat(actionMessageMatcher)); Mockito.reset(errors); loanPrdActionForm.setGracePeriodType(GraceType.GRACEONALLREPAYMENTS.getValueAsString()); loanPrdActionForm.setCanConfigureVariableInstallments(true); loanPrdActionForm.setInterestTypes(InterestType.COMPOUND.getValueAsString()); loanPrdActionForm.validateInterestTypeForGracePeriods(errors, Locale.getDefault()); Mockito.verify(errors).add(Mockito.anyString(), Mockito.argThat(actionMessageMatcher)); Mockito.reset(errors); loanPrdActionForm.setGracePeriodType(GraceType.NONE.getValueAsString()); loanPrdActionForm.setCanConfigureVariableInstallments(false); loanPrdActionForm.setInterestTypes(InterestType.DECLINING_EPI.getValueAsString()); loanPrdActionForm.validateInterestTypeForGracePeriods(errors, Locale.getDefault()); Mockito.verifyZeroInteractions(errors); Mockito.reset(errors); }
@Test public void processValidModel() throws IOException { final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Mockito.mock(HttpServletResponse.class, Mockito.RETURNS_DEEP_STUBS); Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); // Test also that ETag header value contains quotes Mockito.doAnswer( new Answer<Void>() { public Void answer(final InvocationOnMock invocation) throws Throwable { LOG.debug("Header: {}", Arrays.toString(invocation.getArguments())); final Object[] arguments = invocation.getArguments(); if (HttpHeader.ETAG.toString().equals(arguments[0])) { final String etagHeaderValue = (String) arguments[1]; Assert.assertTrue(etagHeaderValue.matches("\".*?\"")); } return null; } }) .when(response) .setHeader(Mockito.anyString(), Mockito.anyString()); Context.set(Context.webContext(request, response, Mockito.mock(FilterConfig.class))); managerFactory.create().process(); }
@Test public void testRestoreInstances_nonNullNonMatchingHandler() throws Exception { // Prepare stuff INotificationMngr notificationMngr = Mockito.mock(INotificationMngr.class); IRandomMngr randomMngr = Mockito.mock(IRandomMngr.class); IMessagingMngr messagingMngr = Mockito.mock(IMessagingMngr.class); ITargetConfigurator targetConfigurator = Mockito.mock(ITargetConfigurator.class); ITargetsMngr targetsMngr = Mockito.mock(ITargetsMngr.class); Mockito.when( targetsMngr.findRawTargetProperties( Mockito.any(Application.class), Mockito.anyString())) .thenReturn(new HashMap<String, String>(0)); IConfigurationMngr configurationMngr = new ConfigurationMngrImpl(); configurationMngr.setWorkingDirectory(this.folder.newFolder()); final TargetHandler targetHandlerArgument = Mockito.mock(TargetHandler.class); Mockito.when(targetHandlerArgument.getTargetId()).thenReturn("some target id"); final TargetHandler targetHandler = Mockito.mock(TargetHandler.class); Mockito.when(targetHandler.getTargetId()).thenReturn("some other target id"); IInstancesMngr mngr = new InstancesMngrImpl( messagingMngr, notificationMngr, targetsMngr, randomMngr, targetConfigurator); ((InstancesMngrImpl) mngr) .setTargetHandlerResolver( new TestTargetResolver() { @Override public TargetHandler findTargetHandler(Map<String, String> targetProperties) throws TargetException { return targetHandler; } }); TestApplication app = new TestApplication(); ManagedApplication ma = new ManagedApplication(app); // One scoped instance has a machine ID (considered as running somewhere) app.getMySqlVm().data.put(Instance.MACHINE_ID, "machine-id"); // Try to restore instances mngr.restoreInstanceStates(ma, targetHandlerArgument); // The handler's ID did not match => no restoration and no use of other mocks Mockito.verify(targetsMngr, Mockito.only()) .findRawTargetProperties(Mockito.eq(app), Mockito.anyString()); Mockito.verify(targetHandler, Mockito.only()).getTargetId(); Mockito.verify(targetHandlerArgument, Mockito.only()).getTargetId(); Mockito.verifyZeroInteractions(messagingMngr); Mockito.verifyZeroInteractions(randomMngr); // No notification was sent since there was no change on Tomcat instances Mockito.verifyZeroInteractions(notificationMngr); Mockito.verifyZeroInteractions(targetConfigurator); }
@Test public void testGetCustomerForCredentialNotExistentCustomer() { when(this.credentialDao.getPunchOutCredential(Mockito.anyString(), Mockito.anyString())) .thenReturn(null); final B2BCustomerModel customerModel = punchoutCredentialService.getCustomerForCredential(credential); assertNull(customerModel); }
@Test public void testGetCustomerForCredential() { when(this.credentialDao.getPunchOutCredential(Mockito.anyString(), Mockito.anyString())) .thenReturn(credentialModel); punchoutCredentialService.setCredentialDao(credentialDao); customerModel = punchoutCredentialService.getCustomerForCredential(credential); assertTrue(customerModel.getEmail().equals(DUMMY_EMAIL)); }
/** AwsRules can cache results of get() and iterator() as same rules. */ @Test public void returnsGetAndIteratorAsSameRules() { final Item item = Mockito.mock(Item.class); final String name = "rule-name-foo"; Mockito.doReturn(new AttributeValue(name)).when(item).get(Mockito.anyString()); final Region region = new RegionMocker().with(item).mock(); final Rules rules = new AwsRules(region, Mockito.mock(SQSClient.class), new URN()); MatcherAssert.assertThat(rules.get(name).name(), Matchers.equalTo(name)); MatcherAssert.assertThat(rules.iterator().next().name(), Matchers.equalTo(name)); Mockito.verify(item, Mockito.times(1)).get(Mockito.anyString()); }
@Test public void noLines() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())).thenReturn(new String[] {}); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() == 0); }
private void buildMockResponsesExistingProfile() throws Exception { // Loading responses for mocks // Tenant setupTenant(); when(tenantManager.getByAccountName(RECEIVER)).thenReturn(tenant); // CredentialStore when(credentialStore.getUriForName(RECEIVER)).thenReturn(RECEIVER_URI); when(credentialStore.getUriForAccountName(RECEIVER, SENDER, tenant)).thenReturn(SENDER_URI); when(credentialStore.getPassword(RECEIVER, SENDER, tenant)).thenReturn(PASSWORD); // Mocking tenantHelper mock(TenantHelper.class); when(TenantHelper.getTenant(new Long(1))).thenReturn(tenant); when(TenantHelper.getCurrentTenant()).thenReturn(tenant); // Mocking: DimeServiceAdapter Token token = new Token("token", "secret"); DimeServiceAdapter mockDimeServiceAdapter = mock(DimeServiceAdapter.class); when(mockDimeServiceAdapter.getUserToken(RECEIVER, Mockito.any(Tenant.class))) .thenReturn(token); PersonContact profile = modelFactory.getNCOFactory().createPersonContact(); when(mockDimeServiceAdapter.getProfile(Mockito.anyString(), Mockito.eq(token))) .thenReturn(profile); // PowerMockito.whenNew(DimeServiceAdapter.class).withAnyArguments().thenReturn(mockDimeServiceAdapter); when(serviceGateway.getDimeServiceAdapter(SENDER)).thenReturn(mockDimeServiceAdapter); User user = new User(); Account account = modelFactory.getDAOFactory().createAccount(SENDER_URI_ON_DEMAND); String name = "dummy"; account.setAccountType(DimeServiceAdapter.NAME); account.setPrefLabel(name + "@" + DimeServiceAdapter.NAME); user.setAccountUri(SENDER_URI_ON_DEMAND); when(userManager.add(Mockito.eq(SENDER))).thenReturn(user); when(userManager.addProfile(Mockito.eq(new URIImpl(SENDER_URI_ON_DEMAND)), Mockito.eq(profile))) .thenReturn(account); // ServiceGateway Vector<LivePost> liveposts = new Vector<LivePost>(); livepost = modelFactory.getDLPOFactory().createLivePost(); liveposts.add(livepost); when(mockDimeServiceAdapter.get( Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.any(Class.class), Mockito.any(Tenant.class))) .thenReturn(liveposts); when(serviceGateway.getDimeServiceAdapter(RECEIVER_URI)).thenReturn(mockDimeServiceAdapter); }
@Test public void doesNotQueryProvisionedEntry() { localDiscoveryAggregator.lookup( lookupCallback, systemServicesDomain, Discovery.INTERFACE_NAME, new DiscoveryQos()); Mockito.verify(discoveryProxyMock, Mockito.never()) .lookup( Mockito.any(Callback.class), Mockito.anyString(), Mockito.anyString(), Mockito.any(DiscoveryQos.class)); }
@Test public void testGetPunchOutCredential() { when(this.credentialDao.getPunchOutCredential(Mockito.anyString(), Mockito.anyString())) .thenReturn(credentialModel); final PunchOutCredentialModel punchoutCredentialModel = punchoutCredentialService.getPunchOutCredential( credential.getDomain(), credential.getIdentity().getContent().get(0).toString()); assertNotNull(punchoutCredentialModel); assertEquals(SHARED_SECRET, punchoutCredentialModel.getSharedsecret()); }
@Test public void testPassingValidAffiliationSendsOutExpectedNotifications() throws Exception { IQ request = toIq( readStanzaAsString("/iq/pubsub/affiliation/affiliationChange.stanza") .replaceFirst("affiliation='member'", "affiliation='moderator'")); NodeAffiliation affiliationMock = Mockito.mock(NodeAffiliation.class); Mockito.when(affiliationMock.getAffiliation()).thenReturn(Affiliations.moderator); Mockito.when(channelManager.nodeExists(node)).thenReturn(true); Mockito.when(channelManager.getUserAffiliation(Mockito.anyString(), Mockito.any(JID.class))) .thenReturn(affiliationMock); ArrayList<NodeSubscription> subscribers = new ArrayList<NodeSubscription>(); subscribers.add(new NodeSubscriptionMock(new JID("*****@*****.**"))); subscribers.add(new NodeSubscriptionMock(new JID("*****@*****.**"))); Mockito.doReturn(new ResultSetImpl<NodeSubscription>(subscribers)) .when(channelManager) .getNodeSubscriptionListeners(Mockito.anyString()); event.setChannelManager(channelManager); event.process(element, jid, request, null); Assert.assertEquals(2, queue.size()); Packet notification = queue.poll(100, TimeUnit.MILLISECONDS); Assert.assertEquals("*****@*****.**", notification.getTo().toString()); notification = queue.poll(100, TimeUnit.MILLISECONDS); Assert.assertEquals("*****@*****.**", notification.getTo().toString()); Assert.assertEquals( node, notification.getElement().element("event").element("affiliations").attributeValue("node")); Assert.assertTrue(notification.toXML().contains(JabberPubsub.NS_PUBSUB_EVENT)); Assert.assertEquals( Affiliations.moderator.toString(), notification .getElement() .element("event") .element("affiliations") .element("affiliation") .attributeValue("affiliation")); Assert.assertEquals( subscriber, notification .getElement() .element("event") .element("affiliations") .element("affiliation") .attributeValue("jid")); }
@Test public void readData5() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())) .thenReturn(new String[] {"1.413913535177E9 UNKNOWN", "1.413913591806E9 CONNECTED"}); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() > 0); }
static RuleFinder ruleFinder() { return when(mock(RuleFinder.class).findByKey(Mockito.anyString(), Mockito.anyString())) .thenAnswer( new Answer<Rule>() { public Rule answer(InvocationOnMock invocation) { Object[] arguments = invocation.getArguments(); return Rule.create( (String) arguments[0], (String) arguments[1], (String) arguments[1]); } }) .getMock(); }
@Test public void ioException() throws IOException { Mockito.when(filereader.fileExist(Mockito.anyString())).thenReturn(true); Mockito.when(filereader.readAllLine(Mockito.anyString())) .thenThrow(new IOException("failed on purpose")); bluetoothReader.setFileReader(filereader); List<BluetoothInfo> bluetoothInfo = bluetoothReader.readData("/", 0, 0); assertTrue(bluetoothInfo.size() == 0); }
@Test public void testLoginFail() throws IllegalActionException, ServiceException { // User clicks login presenter.onLoginClick(); // Login dialog appears verify(loginDialog).showCentered(); // User fills login form and he submits it presenter.onLogin("unknow user", "unknown password"); // Alert dialog is shown verify(alertDialog).center(Mockito.anyString(), Mockito.anyString()); }
@Test public void simulationStatusShouldBeSimulationFinishedAfterInitialising() throws DateTimeParseException, FileNotFoundException, IOException { // given Mockito.doNothing().when(dataProvider).readDataFromFile(Mockito.anyString()); Mockito.when(dataProvider.getEarliestDate()).thenReturn(LocalDate.parse("2013-12-30")); Mockito.when(dataProvider.getLatestDate()).thenReturn(LocalDate.parse("2013-01-02")); // when stockExchange.initialise("Test"); // then Mockito.verify(dataProvider).readDataFromFile(Mockito.anyString()); assertEquals(SimulationStatus.SIMULATION_FINISHED, stockExchange.getSimulationStatus()); }