@Before public void setUp() throws Exception { WXEnvironment.sApplication = RuntimeEnvironment.application; WXSDKInstance instance = Mockito.mock(WXSDKInstance.class); Mockito.when(instance.getContext()).thenReturn(RuntimeEnvironment.application); mParentDomObj = Mockito.spy(new WXDomObject()); Mockito.when(mParentDomObj.getPadding()).thenReturn(new Spacing()); Mockito.when(mParentDomObj.getBorder()).thenReturn(new Spacing()); Mockito.when(mParentDomObj.clone()).thenReturn(mParentDomObj); mParentDomObj.ref = "_root"; mDomObject = Mockito.spy(new WXTextDomObject()); mDomObject.ref = "1"; mDomObject.addEvent(Constants.Event.CLICK); Mockito.when(mDomObject.clone()).thenReturn(mDomObject); Mockito.when(mDomObject.getPadding()).thenReturn(new Spacing()); Mockito.when(mDomObject.getBorder()).thenReturn(new Spacing()); Mockito.when(mDomObject.getMargin()).thenReturn(new Spacing()); Mockito.when(mDomObject.getLayoutWidth()).thenReturn(100f); Mockito.when(mDomObject.getLayoutHeight()).thenReturn(100f); mParent = new WXDiv(instance, mParentDomObj, null, false); mParent.createView(null, -1); mWXText = new WXText(instance, mDomObject, mParent, false); mWXText.bindHolder(new SimpleComponentHolder(WXText.class)); assertNotNull(instance.getContext()); }
/** Test check if Overwriting of unique key attribute cache is working */ @Test public void testOverwriteUniqueKeyAttributeCache() { final ComposedType priceRowComposedTypeSpy = Mockito.spy(TypeManager.getInstance().getComposedType(PriceRow.class)); final CatalogManager catalogManager = CatalogManager.getInstance(); final Map args = new HashMap(); args.put(CatalogVersionSyncJob.CODE, "foo"); args.put(CatalogVersionSyncJob.SOURCEVERSION, srcCatalogVersion); args.put(CatalogVersionSyncJob.TARGETVERSION, tgtCatalogVersion); args.put(CatalogVersionSyncJob.MAXTHREADS, Integer.valueOf(1)); final CatalogVersionSyncJob job = catalogManager.createCatalogVersionSyncJob(args); final CatalogVersionSyncCronJob cjob = (CatalogVersionSyncCronJob) job.newExecution(); ctx = Mockito.spy(new CatalogVersionSyncCopyContext(job, cjob, null)); Mockito.when(priceRowComposedTypeSpy.getAttributeDescriptorsIncludingPrivate()) .thenReturn(Collections.EMPTY_SET); Mockito.when(priceRowSpy.getComposedType()).thenReturn(priceRowComposedTypeSpy); ctx.queryNonCatalogItemCopy(priceRowSpy); ctx.queryCatalogItemCopy(priceRowSpy); }
@Test public void shouldSaveCommands() { // Given String msg = "{ \n" + " \"messageBroadcast\":{ \n" + " \"cameraInfos\":{ \n" + " \"target\":{ \n" + " \"x\":0,\n" + " \"y\":0,\n" + " \"z\":0\n" + " },\n" + " \"camPos\":{ \n" + " \"x\":2283.8555345202267,\n" + " \"y\":1742.2368392950543,\n" + " \"z\":306.5925754554133\n" + " },\n" + " \"camOrientation\":{ \n" + " \"x\":-0.16153026619659236,\n" + " \"y\":0.9837903505522302,\n" + " \"z\":0.07787502335635015\n" + " },\n" + " \"layers\":\"create layer\",\n" + " \"colourEditedObjects\":true,\n" + " \"clipping\":\"1\",\n" + " \"explode\":\"3\",\n" + " \"smartPath\":[ \n" + " \"9447-9445-9441\",\n" + " \"9447-9445-9443\",\n" + " \"9447-9445-9444\",\n" + " \"9446\"\n" + " ]\n" + " }\n" + " }\n" + "}"; JsonObject jsObj = Json.createReader(new StringReader(msg)).readObject(); JsonObject messageBroadcast = jsObj.containsKey("messageBroadcast") ? jsObj.getJsonObject("messageBroadcast") : null; CollaborativeMessage collaborativeMessage = Mockito.spy( new CollaborativeMessage( ChannelMessagesType.COLLABORATIVE_COMMANDS, "key-12545695-7859-458", messageBroadcast, "slave1")); CollaborativeRoom room = Mockito.spy(new CollaborativeRoom(master)); // When room.addSlave(slave1); room.addSlave(slave2); JsonObject commands = collaborativeMessage.getMessageBroadcast(); room.saveCommand(commands); Assert.assertTrue(room.getCommands().entrySet().size() == 1); }
@Test public void shouldReturnFourRooms() { // Given CollaborativeRoom collaborativeRoom1 = Mockito.spy(new CollaborativeRoom(master)); CollaborativeRoom collaborativeRoom2 = Mockito.spy(new CollaborativeRoom(master)); CollaborativeRoom collaborativeRoom3 = Mockito.spy(new CollaborativeRoom(master)); CollaborativeRoom collaborativeRoom4 = Mockito.spy(new CollaborativeRoom(master)); // Then Assert.assertTrue(CollaborativeRoom.getAllCollaborativeRooms().size() == 4); }
@Test public void shouldDeleteRooms() { // Given CollaborativeRoom collaborativeRoom1 = Mockito.spy(new CollaborativeRoom(master)); CollaborativeRoom collaborativeRoom2 = Mockito.spy(new CollaborativeRoom(master)); CollaborativeRoom collaborativeRoom3 = Mockito.spy(new CollaborativeRoom(master)); CollaborativeRoom collaborativeRoom4 = Mockito.spy(new CollaborativeRoom(master)); // When collaborativeRoom1.delete(); collaborativeRoom2.delete(); // Then Assert.assertTrue(CollaborativeRoom.getAllCollaborativeRooms().size() == 2); }
@Test public void shouldReturnNotNullCollaborativeRoom() { // Given CollaborativeRoom collaborativeRoom = Mockito.spy(new CollaborativeRoom(master)); // Then Assert.assertTrue(CollaborativeRoom.getByKeyName(collaborativeRoom.getKey()) != null); }
@Override public void onStartInput(EditorInfo attribute, boolean restarting) { mEditorInfo = attribute; if (restarting || mInputConnection == null) mInputConnection = Mockito.spy(new TestInputConnection(this)); super.onStartInput(attribute, restarting); }
@Test @Transactional @Rollback(value = true) @DirtiesContext(hierarchyMode = HierarchyMode.CURRENT_LEVEL) public void test_Pageable_GetAllRecentUpdate() throws Exception { final int count = 10; Map<NEntityReference, Persistable<Long>> persistableMap = Maps.newHashMap(); for (int it = 0; it < count; it++) { final Persistable<Long> persistable = this.getSpiedPersistableFromSupported(it); Mockito.when(persistable.getId()).thenReturn((long) (it + 1)); final NEntityReference ref = (NEntityReference) this.entityReferenceHelper.toReference(persistable); this.recentlyUpdatedService.newRecentUpdate(persistable); persistableMap.put(ref, persistable); } final EntityReferenceHelper spy = Mockito.spy(this.entityReferenceHelper); for (final NEntityReference ref : persistableMap.keySet()) { Mockito.when(spy.fromReference(ref)).thenReturn(persistableMap.get(ref)); } ReflectionTestUtils.setField(this.recentlyUpdatedService, "entityReferenceHelper", spy); final Page<RecentUpdateBean> recentlyUpdated = this.recentlyUpdatedService.getRecentlyUpdated(new PageRequest(0, 50)); Assert.assertNotNull(recentlyUpdated); Assert.assertTrue(recentlyUpdated.getNumberOfElements() > 0); Assert.assertEquals(count, recentlyUpdated.getNumberOfElements()); }
@Test public void testEstablishRouteViaProxyTunnelRetryOnAuthChallengeNonPersistentConnection() throws Exception { final AuthState authState = new AuthState(); final HttpRoute route = new HttpRoute(target, null, proxy, true); final HttpClientContext context = new HttpClientContext(); final HttpRequestWrapper request = HttpRequestWrapper.wrap(new HttpGet("http://bar/test")); final HttpResponse response1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 401, "Huh?"); final InputStream instream1 = Mockito.spy(new ByteArrayInputStream(new byte[] {1, 2, 3})); response1.setEntity(EntityBuilder.create().setStream(instream1).build()); final HttpResponse response2 = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK"); Mockito.when(managedConn.isOpen()).thenReturn(Boolean.TRUE); Mockito.when( proxyAuthStrategy.isAuthenticationRequested( Mockito.eq(proxy), Mockito.same(response1), Mockito.<HttpClientContext>any())) .thenReturn(Boolean.TRUE); Mockito.when( reuseStrategy.keepAlive(Mockito.<HttpResponse>any(), Mockito.<HttpClientContext>any())) .thenReturn(Boolean.FALSE); Mockito.when( requestExecutor.execute( Mockito.<HttpRequest>any(), Mockito.<HttpClientConnection>any(), Mockito.<HttpClientContext>any())) .thenReturn(response1, response2); mainClientExec.establishRoute(authState, managedConn, route, request, context); Mockito.verify(connManager).connect(managedConn, route, 0, context); Mockito.verify(connManager).routeComplete(managedConn, route, context); Mockito.verify(instream1, Mockito.never()).close(); Mockito.verify(managedConn).close(); }
@Override public View onCreateCandidatesView() { View spiedRootView = Mockito.spy(super.onCreateCandidatesView()); mMockCandidateView = Mockito.mock(CandidateView.class); Mockito.doReturn(mMockCandidateView).when(spiedRootView).findViewById(R.id.candidates); return spiedRootView; }
@Test public void testEquivalent() throws ResourceNotFoundException { Sensor newSensor = Mockito.mock(Sensor.class); Map<String, Object> props = new HashMap<>(); props.put("fuelType", "diesel"); props.put("constructionYear", 2015); props.put("engineDisplacement", 1234); props.put("model", "Dito"); props.put("manufacturer", "Vito"); Mockito.when(newSensor.getProperties()).thenReturn(props); SensorDao dao = createDao(); CarSimilarityServiceImpl service = new CarSimilarityServiceImpl(dao); CarSimilarityServiceImpl serviceMock = Mockito.spy(service); serviceMock.setSimilarityDefinition("/car-similarity-test.json"); Sensor equi = serviceMock.resolveEquivalent(newSensor); Assert.assertThat(equi, Matchers.is(oldSensor)); props.put("manufacturer", "vito mobile "); Sensor similar = serviceMock.resolveEquivalent(newSensor); Assert.assertThat(similar, Matchers.is(oldSensor)); Mockito.verify(serviceMock, Mockito.times(1)) .isManufacturerSimilar(Mockito.any(String.class), Mockito.any(String.class)); }
@Test @Category(UnitTest.class) public void testProcess() throws Exception { CustomScriptGetListProcesslet processlet = Mockito.spy(new CustomScriptGetListProcesslet()); doThrow( new Exception( "Mock Test Error for CustomScriptGetListProcessletTest. (Not real error)")) .when(processlet) .getRequest(); LinkedList<ProcessletInput> allInputs = new LinkedList<ProcessletInput>(); ProcessletInputs in = new ProcessletInputs(allInputs); ProcessDefinition def = new ProcessDefinition(); def.setOutputParameters(new OutputParameters()); LinkedList<ProcessletOutput> allOutputs = new LinkedList<ProcessletOutput>(); allOutputs.add(WpsUtils.createLiteralOutput("SCRIPT_LIST")); final ProcessletOutputs out = new ProcessletOutputs(def, allOutputs); processlet.process(in, out, new ProcessExecution(null, null, null, null, out)); final String responseStr = ((LiteralOutputImpl) out.getParameter("SCRIPT_LIST")).getValue(); assertTrue( responseStr.equals( "Failed: Mock Test Error for CustomScriptGetListProcessletTest. (Not real error)")); }
@Test public void testCopyArtifact() throws OseeCoreException { String guid = GUID.create(); ArtifactData data = Mockito.mock(ArtifactData.class); VersionData version = Mockito.mock(VersionData.class); when(data.getVersion()).thenReturn(version); when(version.getBranchId()).thenReturn(111L); Artifact sourceArtifact = Mockito.spy(new ArtifactImpl(null, data, null, provider)); when(data.getGuid()).thenReturn(guid); List<? extends IAttributeType> copyTypes = Arrays.asList(CoreAttributeTypes.Active, CoreAttributeTypes.Name); when(sourceArtifact.getExistingAttributeTypes()).thenAnswer(answerValue(copyTypes)); when(artifact2.getOrcsData()).thenReturn(data); when(data.isUseBackingData()).thenReturn(false); when(txData.isCommitInProgress()).thenReturn(false); when(txData.getTxState()).thenReturn(TxState.NEW_TX); when(txData.getWriteable(sourceArtifact)).thenReturn(null); when(artifactFactory.copyArtifact(session, sourceArtifact, copyTypes, branch)) .thenReturn(artifact2); when(proxyManager.asExternalArtifact(session, artifact2)).thenReturn(readable2); ArtifactReadable actual = txDataManager.copyArtifact(txData, branch, sourceArtifact); verify(txData).getWriteable(sourceArtifact); verify(artifactFactory).copyArtifact(session, sourceArtifact, copyTypes, branch); assertEquals(readable2, actual); }
@Test public void testSpy() { // spy应尽量少用,可用来处理遗留代码 (没有使用mock生成的对象) List list = new LinkedList(); // 监控一个真实的对象 List spy = Mockito.spy(list); // 可以为某些函数打桩 when(spy.size()).thenReturn(100); // 在监控真实对象上使用when会报错,可以使用onReturn、Answer、Throw()函数族来进行打桩 // 不能:因为当调用spy.get(0)时会调用真实对象的get(0)函数,此时会发生IndexOutOfBoundsException异常,因为真实List对象是空的 // when(spy.get(0)).thenReturn("foo"); doReturn("foo").when(spy).get(0); System.out.println(spy.get(0)); // Mockito并不会为真实对象代理函数(Method)调用,实际上它会复制真实对象。 // 当你在监控一个真实对象时,你想为这个真实对象的函数做测试桩,那么就是在自找麻烦。 // 通过spy对象调用真实对象的函数 spy.add("one"); spy.add("two"); System.out.println(spy.get(0)); System.out.println(spy.size()); // 交互验证 verify(spy).add("one"); verify(spy).add("two"); }
@Test public void testCommandDetection() throws Exception { TestPlugin plugin = PowerMockito.mock(TestPlugin.class); CommandHandler ch = Mockito.spy( new CommandHandler(plugin) { { newKey("pb", true); getKey("pb").newKey("reload", true); } @Override protected boolean register(CommandInfo command) { return false; // To change body of implemented methods use File | Settings | File // Templates. } }); String[] res = ch.commandDetection(new String[] {"pb"}); assertEquals(res.length, 1); assertEquals(res[0], "pb"); res = ch.commandDetection(new String[] {"pb", "reload"}); assertEquals(res.length, 1); assertEquals(res[0], "pb reload"); res = ch.commandDetection(new String[] {"pb", "reload", "poop"}); assertEquals(res.length, 2); assertEquals(res[0], "pb reload"); assertEquals(res[1], "poop"); }
@BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0) @Test public void validateRetieveItemWithLastAccessUpdateTimeDelay() throws Exception { // need to ensure we wait 100 ms int wait = 100; ((DefaultAttributesHandler) repository.getAttributesHandler()).setLastRequestedResolution(wait); Thread.sleep(wait); AttributeStorage attributeStorageSpy = Mockito.spy(repository.getAttributesHandler().getAttributeStorage()); repository.getAttributesHandler().setAttributeStorage(attributeStorageSpy); ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath); resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1"); AbstractStorageItem storageItem = localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest); MatcherAssert.assertThat(storageItem, Matchers.notNullValue()); MatcherAssert.assertThat( storageItem.getLastRequested(), Matchers.greaterThan(originalLastAccessTime)); Mockito.verify(attributeStorageSpy, Mockito.times(1)) .putAttributes(Mockito.<RepositoryItemUid>any(), Mockito.<Attributes>any()); Mockito.verify(attributeStorageSpy, Mockito.times(1)) .getAttributes(Mockito.<RepositoryItemUid>any()); }
@BenchmarkOptions(benchmarkRounds = 10, warmupRounds = 1) @Test public void validateRetieveItemWithOutLastAccessUpdateTimeDelay() throws LocalStorageException, ItemNotFoundException, IOException { // do the test, but make sure the _iterations_ will not get out of the "resolution" span! // Note: this test is just broken as is, what guarantees it will finish the cycles in given X // millis? // Meaning, the assertions + rounds is wrong. ((DefaultAttributesHandler) repository.getAttributesHandler()) .setLastRequestedResolution(30000L); AttributeStorage attributeStorageSpy = Mockito.spy(repository.getAttributesHandler().getAttributeStorage()); repository.getAttributesHandler().setAttributeStorage(attributeStorageSpy); ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath); resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1"); AbstractStorageItem storageItem = localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest); MatcherAssert.assertThat(storageItem, Matchers.notNullValue()); MatcherAssert.assertThat( storageItem.getLastRequested(), Matchers.equalTo(originalLastAccessTime)); Mockito.verify(attributeStorageSpy, Mockito.times(0)) .putAttributes(Mockito.<RepositoryItemUid>any(), Mockito.<Attributes>any()); Mockito.verify(attributeStorageSpy, Mockito.times(1)) .getAttributes(Mockito.<RepositoryItemUid>any()); }
/** * Test that if we fail a flush, abort gets set on close. * * @see <a href="https://issues.apache.org/jira/browse/HBASE-4270">HBASE-4270</a> * @throws IOException * @throws NodeExistsException * @throws KeeperException */ @Test public void testFailedFlushAborts() throws IOException, NodeExistsException, KeeperException { final Server server = new MockServer(HTU, false); final RegionServerServices rss = HTU.createMockRegionServerService(); HTableDescriptor htd = TEST_HTD; final HRegionInfo hri = new HRegionInfo(htd.getTableName(), HConstants.EMPTY_END_ROW, HConstants.EMPTY_END_ROW); HRegion region = HTU.createLocalHRegion(hri, htd); try { assertNotNull(region); // Spy on the region so can throw exception when close is called. HRegion spy = Mockito.spy(region); final boolean abort = false; Mockito.when(spy.close(abort)).thenThrow(new RuntimeException("Mocked failed close!")); // The CloseRegionHandler will try to get an HRegion that corresponds // to the passed hri -- so insert the region into the online region Set. rss.addToOnlineRegions(spy); // Assert the Server is NOT stopped before we call close region. assertFalse(server.isStopped()); CloseRegionHandler handler = new CloseRegionHandler(server, rss, hri, false, false, -1); boolean throwable = false; try { handler.process(); } catch (Throwable t) { throwable = true; } finally { assertTrue(throwable); // Abort calls stop so stopped flag should be set. assertTrue(server.isStopped()); } } finally { HRegion.closeHRegion(region); } }
@Test public void toByteArray() throws Exception { byte[] data = {'a', 'b', 'c'}; InputStream in = Mockito.spy(new ByteArrayInputStream(data)); assertArrayEquals(data, IOUtils.toByteArray(in)); verify(in, never()).close(); in = Mockito.spy(new ByteArrayInputStream(data)); assertArrayEquals(data, IOUtils.toByteArray(in, false)); verify(in, never()).close(); in = Mockito.spy(new ByteArrayInputStream(data)); assertArrayEquals(data, IOUtils.toByteArray(in, true)); verify(in).close(); }
public MockCFApplication defApp(String name) { MockCFApplication existing = appsByName.get(name); if (existing == null) { appsByName.put(name, existing = Mockito.spy(new MockCFApplication(owner, this, name))); } return existing; }
@Test public void testUnregisterTwice() throws Exception { AeroGearGCMPushConfiguration config = new AeroGearGCMPushConfiguration() .setSenderId(TEST_SENDER_ID) .setVariantID(TEST_SENDER_VARIANT) .setSecret(TEST_SENDER_PASSWORD) .setPushServerURI(new URI("https://testuri")); AeroGearGCMPushRegistrar registrar = (AeroGearGCMPushRegistrar) config.asRegistrar(); CountDownLatch latch = new CountDownLatch(1); StubHttpProvider provider = new StubHttpProvider(); UnitTestUtils.setPrivateField(registrar, "httpProviderProvider", provider); StubInstanceIDProvider instanceIdProvider = new StubInstanceIDProvider(); UnitTestUtils.setPrivateField(registrar, "instanceIdProvider", instanceIdProvider); VoidCallback callback = new VoidCallback(latch); AeroGearGCMPushRegistrar spy = Mockito.spy(registrar); spy.register(super.getActivity(), callback); latch.await(1, TimeUnit.SECONDS); latch = new CountDownLatch(2); callback = new VoidCallback(latch); spy.unregister(super.getActivity(), callback); spy.unregister(super.getActivity(), callback); latch.await(4, TimeUnit.SECONDS); Assert.assertNotNull(callback.exception); Assert.assertTrue(callback.exception instanceof IllegalStateException); }
@Test @Category(UnitTest.class) public void testProcess() throws Exception { String params = "{\"INPUT1_TYPE\":\"DB\",\"INPUT1\":\"DcGisRoads\",\"INPUT2_TYPE\":\"DB\",\"INPUT2\":\"DcTigerRoads\","; params += "\"OUTPUT_NAME\":\"Merged_Roads_e0d\",\"CONFLATION_TYPE\":\"Reference\",\"MATCH_THRESHOLD\":\"0.6\",\"MISS_THRESHOLD\":\"0.6\"}"; String jobArgs = "\"exec\":\"makeconflate\",\"params\":[{\"CONFLATION_TYPE\":\"Reference\"}," + "{\"MATCH_THRESHOLD\":\"0.6\"},{\"INPUT1_TYPE\":\"DB\"},{\"MISS_THRESHOLD\":\"0.6\"}," + "{\"INPUT2_TYPE\":\"DB\"},{\"INPUT2\":\"DcTigerRoads\"},{\"INPUT1\":\"DcGisRoads\"}," + "{\"OUTPUT_NAME\":\"Merged_Roads_e0d\"},{\"IS_BIG\":\"false\"}],\"exectype\":\"make\"}," + "{\"class\":\"hoot.services.controllers.job.ReviewResource\",\"method\":\"prepareItemsForReview\",\"params\":" + "[{\"isprimitivetype\":\"false\",\"value\":\"Merged_Roads_e0d\",\"paramtype\":\"java.lang.String\"}," + "{\"isprimitivetype\":\"true\",\"value\":false,\"paramtype\":\"java.lang.Boolean\"}],\"exectype\":\"reflection\"}," + "{\"class\":\"hoot.services.controllers.ingest.RasterToTilesService\",\"method\":\"ingestOSMResourceDirect\",\"params\":" + "[{\"isprimitivetype\":\"false\",\"value\":\"Merged_Roads_e0d\",\"paramtype\":\"java.lang.String\"}],\"exectype\":\"reflection\"}]"; ConflationResource spy = Mockito.spy(new ConflationResource()); Mockito.doNothing().when((JobControllerBase) spy).postChainJobRquest(anyString(), anyString()); Response resp = spy.process(params); String result = resp.getEntity().toString(); JSONParser parser = new JSONParser(); JSONObject o = (JSONObject) parser.parse(result); String jobId = o.get("jobid").toString(); verify(spy).postChainJobRquest(Matchers.matches(jobId), Matchers.endsWith(jobArgs)); }
/** * Run the void blur() method test. * * @throws Exception */ @Test public void testBlur() throws Exception { final ExtJSComponent result = Mockito.spy(new ExtJSComponent(driver, cmpIdBy)); result.blur(); Mockito.verify(result).fireEvent("blur"); }
@Before public void setUp() throws Exception { final CatalogManager catalogManager = CatalogManager.getInstance(); final Catalog catalog = catalogManager.createCatalog("PartOfTest"); srcCatalogVersion = catalogManager.createCatalogVersion(catalog, "ver1", null); srcCatalogVersion.setLanguages(Collections.singletonList(getOrCreateLanguage("de"))); tgtCatalogVersion = catalogManager.createCatalogVersion(catalog, "ver2", null); tgtCatalogVersion.setLanguages(Collections.singletonList(getOrCreateLanguage("de"))); LOG.info("Creating product"); final ComposedType composedType = TypeManager.getInstance().getComposedType(Product.class); final Product productOne = createProduct("Product-One", composedType); final Product productTwo = createProduct("Product-Two", composedType); LOG.info("Creating product reference "); catalogManager.createProductReference("foo", productOne, productTwo, Integer.valueOf(1)); LOG.info("Done catalog creation."); final Europe1PriceFactory europe1 = Europe1PriceFactory.getInstance(); final Currency currency = C2LManager.getInstance().createCurrency("europe1/dr"); final Unit unit = ProductManager.getInstance().createUnit(null, "europe1/u", "typ"); final EnumerationValue enumValue = EnumerationManager.getInstance() .createEnumerationValue(Europe1Constants.TYPES.DISCOUNT_USER_GROUP, "test"); priceRowSpy = Mockito.spy( europe1.createPriceRow( productTwo, null, null, enumValue, 0, currency, unit, 1, true, null, 0)); }
@Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { if (spyNames != null && spyNames.contains(beanName)) { return Mockito.spy(bean); } return bean; }
@Test public void shouldReturnMaster() { // Given CollaborativeRoom collaborativeRoom1 = Mockito.spy(new CollaborativeRoom(master)); // Then Assert.assertTrue("master1".equals(collaborativeRoom1.getLastMaster())); }
@Test public void testWildCardMatchingWithQuery() throws Exception { final HttpRequestHandler h1 = Mockito.mock(HttpRequestHandler.class); final HttpRequestHandler h2 = Mockito.mock(HttpRequestHandler.class); final HttpRequestHandler def = Mockito.mock(HttpRequestHandler.class); final UriPatternMatcher<HttpRequestHandler> matcher = Mockito.spy(new UriPatternMatcher<HttpRequestHandler>()); final UriHttpRequestHandlerMapper registry = new UriHttpRequestHandlerMapper(matcher); registry.register("*", def); registry.register("*.view", h1); registry.register("*.form", h2); HttpRequestHandler h; h = registry.lookup(new BasicHttpRequest("GET", "/that.view?param=value")); Assert.assertNotNull(h); Assert.assertTrue(h1 == h); h = registry.lookup(new BasicHttpRequest("GET", "/that.form?whatever")); Assert.assertNotNull(h); Assert.assertTrue(h2 == h); h = registry.lookup(new BasicHttpRequest("GET", "/whatever")); Assert.assertNotNull(h); Assert.assertTrue(def == h); }
@Test public void shouldReturnNotNullMasterName() { // Given CollaborativeRoom nullCollaborativeRoom = Mockito.spy(new CollaborativeRoom(master)); // then Assert.assertTrue(!nullCollaborativeRoom.getMasterName().isEmpty()); }
/* * Test the behavior when the access token is invalid (expired) for the refresh token behavior The case is: - Connect to the service (authenticate) - Edit the token to be * invalid In this part the connector should try to refresh the access token using the refresh token and then call again the same operation with the same parameters - Validate * that the operation executes */ @Test public void refreshAccessToken() throws ObjectStoreException, HubSpotConnectorException, HubSpotConnectorNoAccessTokenException, HubSpotConnectorAccessTokenExpiredException { // Mock the client to check how many times refresh it's invoked final HubSpotClientsManager hcm = connector.getClientsManager(); HubSpotClient hc = hcm.getClient(USER_ID); hc = Mockito.spy(hc); // Save the mocked client hcm.addClient(USER_ID, hc); final OAuthCredentials credentials = (OAuthCredentials) credentialsMap.retrieve(USER_ID); credentials.setAccessToken("you-will-fail-token-muajuajua"); credentialsMap.store(USER_ID, credentials); final ContactList cl = connector.getAllContacts(USER_ID, null, null); Assert.assertNotNull(cl); createRetrieveDeleteContact(); // Refresh token only suppose to call one time Mockito.verify(hc, Mockito.times(1)) .refreshToken(Matchers.any(HubSpotCredentialsManager.class), Matchers.anyString()); }
@Before public void beforeEachTest() { logger.debug("Before Test"); dataSource = Mockito.mock(DataSource.class); Connection connection = Mockito.mock(Connection.class); DatabaseMetaData databaseMetaData = Mockito.mock(DatabaseMetaData.class); try { Mockito.stub(dataSource.getConnection()).toReturn(connection); Mockito.stub(connection.getMetaData()).toReturn(databaseMetaData); } catch (Exception e) { logger.error("Error Occurred Stubbing Datasource or connection", e); } transactionManager = new DataSourceTransactionManager(); transactionManager.setTransactionSynchronization( DataSourceTransactionManager.SYNCHRONIZATION_ON_ACTUAL_TRANSACTION); transactionManager = Mockito.spy(transactionManager); transactionManager.setDataSource(dataSource); MapJobInstanceDao jobInstanceDao = new MapJobInstanceDao(); MapJobExecutionDao jobExecutionDao = new MapJobExecutionDao(); MapStepExecutionDao stepExecutionDao = new MapStepExecutionDao(); MapExecutionContextDao ecDao = new MapExecutionContextDao(); jobLauncherTestUtils = new JobLauncherTestUtils(); jobRepository = new SimpleJobRepository(jobInstanceDao, jobExecutionDao, stepExecutionDao, ecDao); jobLauncherTestUtils.setJobRepository(jobRepository); // jobConfig = new ProductJobConfig(); // jobConfig.setJobRepository(jobRepository); executionContext = new ExecutionContext(); }