@Test public void parseInternal_withMinimalConfig_shouldCreateDefaultTemplate() throws Exception { // Arrange DefaultListableBeanFactory registry = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry); // Act reader.loadBeanDefinitions( new ClassPathResource(getClass().getSimpleName() + "-minimal.xml", getClass())); // Assert NotificationMessagingTemplate notificationMessagingTemplate = registry.getBean(NotificationMessagingTemplate.class); assertSame( registry.getBean(AmazonSNSClient.class), ReflectionTestUtils.getField(notificationMessagingTemplate, "amazonSns")); Object cachingDestinationResolverProxy = ReflectionTestUtils.getField(notificationMessagingTemplate, "destinationResolver"); Object targetDestinationResolver = ReflectionTestUtils.getField(cachingDestinationResolverProxy, "targetDestinationResolver"); assertEquals( registry.getBean(GlobalBeanDefinitionUtils.RESOURCE_ID_RESOLVER_BEAN_NAME), ReflectionTestUtils.getField(targetDestinationResolver, "resourceIdResolver")); assertTrue( StringMessageConverter.class.isInstance( notificationMessagingTemplate.getMessageConverter())); assertEquals( String.class, ReflectionTestUtils.getField( notificationMessagingTemplate.getMessageConverter(), "serializedPayloadClass")); }
@Test public void testParseWithDefaults() throws Exception { SimpleMessageListenerContainer container = beanFactory.getBean("container4", SimpleMessageListenerContainer.class); assertEquals(1, ReflectionTestUtils.getField(container, "concurrentConsumers")); assertEquals(true, ReflectionTestUtils.getField(container, "defaultRequeueRejected")); }
@Test public void testParseWithDefaultQueueRejectedFalse() throws Exception { SimpleMessageListenerContainer container = beanFactory.getBean("container5", SimpleMessageListenerContainer.class); assertEquals(1, ReflectionTestUtils.getField(container, "concurrentConsumers")); assertEquals(false, ReflectionTestUtils.getField(container, "defaultRequeueRejected")); assertFalse(container.isChannelTransacted()); }
@Test public void testSetTypeConvertersInOrder() throws Exception { List org = (List) ReflectionTestUtils.getField(converterHelper, "typeConvertersInOrder"); TypeConverter typeConverter = mock(TypeConverter.class); assertThat(org.size()).isEqualTo(0); // default is empty converterHelper.setTypeConvertersInOrder(Collections.singletonList(typeConverter)); List res = (List) ReflectionTestUtils.getField(converterHelper, "typeConvertersInOrder"); assertThat(res.size()).isEqualTo(1); assertThat((Object) res).isInstanceOf(LockableList.class); assertThat((Boolean) ReflectionTestUtils.getField(res, "readOnly")).isTrue(); }
/** * @see <a href="https://jira.spring.io/browse/DATACASS-226">DATACASS-226</a> * @see <a href="https://jira.spring.io/browse/DATACASS-263">DATACASS-263</a> * @throws Exception */ @Test public void shouldSetAuthentication() throws Exception { CassandraCqlClusterFactoryBean bean = new CassandraCqlClusterFactoryBean(); bean.setUsername("user"); bean.setPassword("password"); bean.afterPropertiesSet(); AuthProvider result = getConfiguration(bean).getProtocolOptions().getAuthProvider(); assertThat(result).isNotNull(); assertThat(ReflectionTestUtils.getField(result, "username")).isEqualTo((Object) "user"); assertThat(ReflectionTestUtils.getField(result, "password")).isEqualTo((Object) "password"); }
@Test public void testUserSpecifiedConfigName() throws Exception { System.setProperty("loader.config.name", "foo"); PropertiesLauncher launcher = new PropertiesLauncher(); assertEquals("my.Application", launcher.getMainClass()); assertEquals("[etc/]", ReflectionTestUtils.getField(launcher, "paths").toString()); }
@SuppressWarnings("unchecked") private List<HttpMessageConverter<?>> extractFormPartConverters( List<HttpMessageConverter<?>> converters) { AllEncompassingFormHttpMessageConverter formConverter = findFormConverter(converters); return (List<HttpMessageConverter<?>>) ReflectionTestUtils.getField(formConverter, "partConverters"); }
@Test public void onDifferentPort() throws Exception { this.applicationContext.register( RootConfig.class, EndpointConfig.class, DifferentPortConfig.class, BaseConfiguration.class, EndpointWebMvcAutoConfiguration.class, ErrorMvcAutoConfiguration.class); this.applicationContext.refresh(); assertContent("/controller", ports.get().server, "controlleroutput"); assertContent("/endpoint", ports.get().server, null); assertContent("/controller", ports.get().management, null); assertContent("/endpoint", ports.get().management, "endpointoutput"); assertContent("/error", ports.get().management, startsWith("{")); ApplicationContext managementContext = this.applicationContext.getBean(ManagementContextResolver.class).getApplicationContext(); List<?> interceptors = (List<?>) ReflectionTestUtils.getField( managementContext.getBean(EndpointHandlerMapping.class), "interceptors"); assertThat(interceptors).hasSize(1); this.applicationContext.close(); assertAllClosed(); }
/** * @see DATADOC-295 * @throws UnknownHostException */ @Test public void mongoUriConstructor() throws UnknownHostException { MongoURI mongoURI = new MongoURI("mongodb://*****:*****@localhost/myDatabase.myCollection"); MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoURI); assertThat( ReflectionTestUtils.getField(mongoDbFactory, "username").toString(), is("myUsername")); assertThat( ReflectionTestUtils.getField(mongoDbFactory, "password").toString(), is("myPassword")); assertThat( ReflectionTestUtils.getField(mongoDbFactory, "databaseName").toString(), is("myDatabase")); assertThat( ReflectionTestUtils.getField(mongoDbFactory, "databaseName").toString(), is("myDatabase")); }
@Test public void testParseWithTx() throws Exception { SimpleMessageListenerContainer container = beanFactory.getBean("container6", SimpleMessageListenerContainer.class); assertTrue(container.isChannelTransacted()); assertEquals(5, ReflectionTestUtils.getField(container, "txSize")); }
private Map<String, Object> getEnvironmentProperties(Class<?> testClass) throws Exception { TestContext context = new ExposedTestContextManager(testClass).getExposedTestContext(); new IntegrationTestPropertiesListener().prepareTestInstance(context); MergedContextConfiguration config = (MergedContextConfiguration) ReflectionTestUtils.getField(context, "mergedContextConfiguration"); return this.loader.extractEnvironmentProperties(config.getPropertySourceProperties()); }
@Test public void testUserSpecifiedJarPath() throws Exception { System.setProperty("loader.path", "jars/app.jar"); System.setProperty("loader.main", "demo.Application"); PropertiesLauncher launcher = new PropertiesLauncher(); assertEquals("[jars/app.jar]", ReflectionTestUtils.getField(launcher, "paths").toString()); launcher.launch(new String[0]); waitFor("Hello World"); }
@Test public void testParseWithAdviceChain() throws Exception { SimpleMessageListenerContainer container = beanFactory.getBean("container3", SimpleMessageListenerContainer.class); Object adviceChain = ReflectionTestUtils.getField(container, "adviceChain"); assertNotNull(adviceChain); assertEquals(3, ((Advice[]) adviceChain).length); assertTrue(TestUtils.getPropertyValue(container, "exclusive", Boolean.class)); }
@Test public void doAppendTest() throws IOException, InterruptedException { DeliveryCallback callback = new DeliveryCallback(); logAppender.doAppend(generateLogEventPack(20), callback); Thread.sleep(3000); CassandraLogEventDao logEventDao = (CassandraLogEventDao) ReflectionTestUtils.getField(logAppender, "logEventDao"); Session session = (Session) ReflectionTestUtils.getField(logEventDao, "session"); ResultSet resultSet = session.execute( QueryBuilder.select() .countAll() .from( KEY_SPACE_NAME, "logs_" + appToken + "_" + Math.abs(configuration.hashCode()))); Row row = resultSet.one(); Assert.assertEquals(20L, row.getLong(0)); Assert.assertEquals(1, callback.getSuccessCount()); }
@Test public void testAnonEverything() throws Exception { SimpleMessageListenerContainer container = beanFactory.getBean( "org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#3", SimpleMessageListenerContainer.class); assertEquals( "ex1", ReflectionTestUtils.getField( ReflectionTestUtils.getField(container, "messageListener"), "responseExchange")); container = beanFactory.getBean( "org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer#4", SimpleMessageListenerContainer.class); assertEquals( "ex2", ReflectionTestUtils.getField( ReflectionTestUtils.getField(container, "messageListener"), "responseExchange")); }
@Test public void closingContextCleansUpLoggingSystem() { System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); this.initializer.onApplicationEvent( new ApplicationStartedEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils.getField(this.initializer, "loggingSystem"); assertThat(loggingSystem.cleanedUp).isFalse(); this.initializer.onApplicationEvent(new ContextClosedEvent(this.context)); assertThat(loggingSystem.cleanedUp).isTrue(); }
@Test public void testWriteConcern() throws Exception { SimpleMongoDbFactory dbFactory = new SimpleMongoDbFactory(new MongoClient("localhost"), "database"); dbFactory.setWriteConcern(WriteConcern.SAFE); dbFactory.getDb(); assertThat( ReflectionTestUtils.getField(dbFactory, "writeConcern"), is((Object) WriteConcern.SAFE)); }
@Test public void testParseWithQueueNames() throws Exception { SimpleMessageListenerContainer container = beanFactory.getBean("container1", SimpleMessageListenerContainer.class); assertEquals(AcknowledgeMode.MANUAL, container.getAcknowledgeMode()); assertEquals(beanFactory.getBean(ConnectionFactory.class), container.getConnectionFactory()); assertEquals(MessageListenerAdapter.class, container.getMessageListener().getClass()); DirectFieldAccessor listenerAccessor = new DirectFieldAccessor(container.getMessageListener()); assertEquals( beanFactory.getBean(TestBean.class), listenerAccessor.getPropertyValue("delegate")); assertEquals("handle", listenerAccessor.getPropertyValue("defaultListenerMethod")); Queue queue = beanFactory.getBean("bar", Queue.class); assertEquals( "[foo, " + queue.getName() + "]", Arrays.asList(container.getQueueNames()).toString()); assertEquals(5, ReflectionTestUtils.getField(container, "concurrentConsumers")); assertEquals(6, ReflectionTestUtils.getField(container, "maxConcurrentConsumers")); assertEquals(1234L, ReflectionTestUtils.getField(container, "startConsumerMinInterval")); assertEquals(2345L, ReflectionTestUtils.getField(container, "stopConsumerMinInterval")); assertEquals(12, ReflectionTestUtils.getField(container, "consecutiveActiveTrigger")); assertEquals(34, ReflectionTestUtils.getField(container, "consecutiveIdleTrigger")); assertEquals(9876L, ReflectionTestUtils.getField(container, "receiveTimeout")); Map<?, ?> consumerArgs = TestUtils.getPropertyValue(container, "consumerArgs", Map.class); assertEquals(1, consumerArgs.size()); Object xPriority = consumerArgs.get("x-priority"); assertNotNull(xPriority); assertEquals(10, xPriority); assertEquals( Long.valueOf(5555), TestUtils.getPropertyValue(container, "recoveryBackOff.interval", Long.class)); assertFalse(TestUtils.getPropertyValue(container, "exclusive", Boolean.class)); assertFalse(TestUtils.getPropertyValue(container, "missingQueuesFatal", Boolean.class)); assertTrue(TestUtils.getPropertyValue(container, "autoDeclare", Boolean.class)); assertEquals(5, TestUtils.getPropertyValue(container, "declarationRetries")); assertEquals(1000L, TestUtils.getPropertyValue(container, "failedDeclarationRetryInterval")); assertEquals(30000L, TestUtils.getPropertyValue(container, "retryDeclarationInterval")); assertEquals( beanFactory.getBean("tagger"), TestUtils.getPropertyValue(container, "consumerTagStrategy")); Collection<?> group = beanFactory.getBean("containerGroup", Collection.class); assertEquals(3, group.size()); assertThat( group, Matchers.contains( beanFactory.getBean("container1"), beanFactory.getBean("testListener1"), beanFactory.getBean("testListener2"))); assertEquals(1235L, ReflectionTestUtils.getField(container, "idleEventInterval")); assertEquals("container1", container.getListenerId()); }
@Test public void testGetToConverter_mapOnly() throws Exception { ReflectionTestUtils.setField( converterHelper, "reflectionHelper", new ReflectionHelper()); // echte gebruiken ((Map<String, TypeConverter>) ReflectionTestUtils.getField(converterHelper, "typeConverterInstances")) .put("always2", new DefaultTypeConverter()); ToConverter res = converterHelper.getToConverter(TaggedPersonTo.class, PersonDomain.class); assertThat(res).isNotNull(); assertThat(res.getToTo()).hasSize(4); assertThat(res.getToTo().get(0)).isInstanceOf(TaggedConverter.class); assertThat(res.getToDomain()).hasSize(3); assertThat(res.getToDomain().get(0)).isInstanceOf(TaggedConverter.class); }
@Test public void parseInternal_withCustomRegion_shouldConfigureDefaultClientWithCustomRegion() throws Exception { // Arrange DefaultListableBeanFactory registry = new DefaultListableBeanFactory(); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(registry); // Act reader.loadBeanDefinitions( new ClassPathResource(getClass().getSimpleName() + "-custom-region.xml", getClass())); // Assert AmazonSNSClient amazonSns = registry.getBean(AmazonSNSClient.class); assertEquals( "https://" + Region.getRegion(Regions.EU_WEST_1).getServiceEndpoint("sns"), ReflectionTestUtils.getField(amazonSns, "endpoint").toString()); }
private static void assertWriteConcern( ClassPathXmlApplicationContext ctx, WriteConcern expectedWriteConcern) { SimpleMongoDbFactory dbFactory = ctx.getBean("first", SimpleMongoDbFactory.class); DB db = dbFactory.getDb(); assertThat(db.getName(), is("db")); WriteConcern configuredConcern = (WriteConcern) ReflectionTestUtils.getField(dbFactory, "writeConcern"); MyWriteConcern myDbFactoryWriteConcern = new MyWriteConcern(configuredConcern); MyWriteConcern myDbWriteConcern = new MyWriteConcern(db.getWriteConcern()); MyWriteConcern myExpectedWriteConcern = new MyWriteConcern(expectedWriteConcern); assertThat(myDbFactoryWriteConcern, is(myExpectedWriteConcern)); assertThat(myDbWriteConcern, is(myExpectedWriteConcern)); assertThat(myDbWriteConcern, is(myDbFactoryWriteConcern)); }
@Test public void testCollectProjects() throws Exception { // given RepositoryWrapper repo = mock(RepositoryWrapper.class); when(repo.getId()).thenReturn(123); when(repo.getName()).thenReturn("awesome"); when(repo.getUrl()).thenReturn(new URL("http://a.com/b.html")); when(repo.getDescription()).thenReturn("cool"); when(repo.getStarsCount()).thenReturn(11); when(repo.getForksCount()).thenReturn(22); when(repo.getLastPushed()).thenReturn(date); when(repo.getPrimaryLanguage()).thenReturn("Go"); when(repo.listLanguages()).thenReturn(toMap("C", 30, "Go", 15, "Java", 4)); when(repo.listCommits()).thenReturn(mockList(GHCommit.class, 2)); when(repo.listContributors()).thenReturn(mockList(Contributor.class, 2)); when(scorer.score(any(Project.class))).thenReturn(55); // when List<Project> projects = new ArrayList<>(task.collectProjects(org(singletonList(repo)))); // then assertThat(projects, hasSize(1)); Project project = projects.get(0); assertThat(project.getGitHubProjectId(), equalTo(123L)); assertThat( project.getSnapshotDate().getTime(), equalTo(((Date) ReflectionTestUtils.getField(task, "snapshotDate")).getTime())); assertThat(project.getName(), equalTo("awesome")); assertThat(project.getUrl(), equalTo("http://a.com/b.html")); assertThat(project.getDescription(), equalTo("cool")); assertThat(project.getStarsCount(), equalTo(11)); assertThat(project.getForksCount(), equalTo(22)); assertThat(project.getLastPushed(), equalTo(date.toString())); assertThat(project.getPrimaryLanguage(), equalTo("Go")); assertThat(project.getLanguageList(), containsInAnyOrder("C", "Go", "Java")); assertThat(project.getCommitsCount(), equalTo(2)); assertThat(project.getContributorsCount(), equalTo(2)); assertThat(project.getScore(), equalTo(55)); }
@Test public void testDefaultConfiguration() { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); this.context.register( AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class); this.context.refresh(); this.context.getBean(AUTHORIZATION_SERVER_CONFIG); this.context.getBean(RESOURCE_SERVER_CONFIG); this.context.getBean(OAuth2MethodSecurityConfiguration.class); ClientDetails config = this.context.getBean(BaseClientDetails.class); AuthorizationEndpoint endpoint = this.context.getBean(AuthorizationEndpoint.class); UserApprovalHandler handler = (UserApprovalHandler) ReflectionTestUtils.getField(endpoint, "userApprovalHandler"); ClientDetailsService clientDetailsService = this.context.getBean(ClientDetailsService.class); ClientDetails clientDetails = clientDetailsService.loadClientByClientId(config.getClientId()); assertThat(AopUtils.isJdkDynamicProxy(clientDetailsService), equalTo(true)); assertThat( AopUtils.getTargetClass(clientDetailsService).getName(), equalTo(ClientDetailsService.class.getName())); assertThat(handler instanceof ApprovalStoreUserApprovalHandler, equalTo(true)); assertThat(clientDetails, equalTo(config)); verifyAuthentication(config); }
@Test public void messageHandlerProcessTest() { BootstrapTransportService bService = new BootstrapTransportService(); KeyStoreService keyStoreService = mock(KeyStoreService.class); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); when(keyStoreService.getPublicKey()).thenReturn(publicKey); when(keyStoreService.getPrivateKey()).thenReturn(privateKey); ReflectionTestUtils.setField(bService, "supportUnencryptedConnection", true); ReflectionTestUtils.setField(bService, "keyStoreService", keyStoreService); ReflectionTestUtils.setField(bService, "properties", new Properties()); bService.lookupAndInit(); MessageHandler handler = (BootstrapTransportService.BootstrapMessageHandler) ReflectionTestUtils.getField(bService, "handler"); SessionInitMessage encryptedSessionInitMessage = mockForSessionInitMessage(true); SessionInitMessage nonEncryptedSessionInitMessage = mockForSessionInitMessage(false); handler.process(encryptedSessionInitMessage); handler.process(nonEncryptedSessionInitMessage); verify(encryptedSessionInitMessage, timeout(1000)).getEncodedMessageData(); verify(nonEncryptedSessionInitMessage, timeout(1000)).getEncodedMessageData(); }
@Test public void shouldSetFieldValidators() { assertFalse(dataDefinition.getField("fieldText").isRequired()); assertFalse(dataDefinition.getField("fieldText").isUnique()); assertTrue(dataDefinition.getField("fieldInteger").isRequired()); assertTrue(dataDefinition.getField("fieldInteger").isUnique()); assertEquals( 0, ((FieldDefinitionImpl) dataDefinition.getField("fieldDatetime")).getValidators().size()); assertEquals( 6, ((FieldDefinitionImpl) dataDefinition.getField("fieldInteger")).getValidators().size()); List<FieldHookDefinition> validators = ((FieldDefinitionImpl) dataDefinition.getField("fieldInteger")).getValidators(); assertThat(validators.get(0), instanceOf(RequiredValidator.class)); assertThat(validators.get(1), instanceOf(UniqueValidator.class)); assertThat(validators.get(2), instanceOf(CustomValidator.class)); testHookDefinition(validators.get(2), "fieldHook", CustomHook.class, "validateField"); assertThat(validators.get(3), instanceOf(LengthValidator.class)); assertEquals(1, getField(validators.get(3), "min")); assertNull(getField(validators.get(3), "is")); assertEquals(3, getField(validators.get(3), "max")); assertThat(validators.get(4), instanceOf(UnscaledValueValidator.class)); assertEquals(2, getField(validators.get(4), "min")); assertNull(getField(validators.get(4), "is")); assertEquals(4, getField(validators.get(4), "max")); assertThat(validators.get(5), instanceOf(RangeValidator.class)); assertEquals(18, getField(validators.get(5), "from")); assertEquals(null, getField(validators.get(5), "to")); assertEquals(false, getField(validators.get(5), "inclusively")); validators = ((FieldDefinitionImpl) dataDefinition.getField("fieldString")).getValidators(); assertEquals(4, validators.size()); assertThat(validators.get(3), instanceOf(RegexValidator.class)); assertEquals("d??p", getField(validators.get(3), "regex")); validators = ((FieldDefinitionImpl) dataDefinition.getField("fieldStringWithoutValidators")) .getValidators(); assertEquals(1, validators.size()); assertThat(validators.get(0), instanceOf(LengthValidator.class)); assertEquals(255, ReflectionTestUtils.getField(validators.get(0), "max")); validators = ((FieldDefinitionImpl) dataDefinition.getField("fieldDecimal")).getValidators(); assertThat(validators.get(0), instanceOf(ScaleValidator.class)); assertEquals(2, getField(validators.get(0), "min")); assertNull(getField(validators.get(0), "is")); assertEquals(4, getField(validators.get(0), "max")); assertThat(validators.get(1), instanceOf(UnscaledValueValidator.class)); assertNull(getField(validators.get(1), "min")); assertEquals(2, getField(validators.get(1), "is")); assertNull(getField(validators.get(1), "max")); validators = ((FieldDefinitionImpl) dataDefinition.getField("fieldDecimalOnlyWithScale")) .getValidators(); assertThat(validators.get(0), instanceOf(ScaleValidator.class)); assertEquals(2, getField(validators.get(0), "min")); assertNull(getField(validators.get(0), "is")); assertEquals(4, getField(validators.get(0), "max")); validators = ((FieldDefinitionImpl) dataDefinition.getField("fieldDecimalWithoutValidators")) .getValidators(); assertEquals(2, validators.size()); }
private <K, V> RedisChannelHandler<K, V> getRedisChannelHandler(RedisConnection<K, V> sync) { InvocationHandler invocationHandler = Proxy.getInvocationHandler(sync); return (RedisChannelHandler<K, V>) ReflectionTestUtils.getField(invocationHandler, "connection"); }
private Channel getChannel(RedisChannelHandler<?, ?> channelHandler) { return (Channel) ReflectionTestUtils.getField(channelHandler.getChannelWriter(), "channel"); }
private String getConnectionState(RedisChannelHandler<?, ?> channelHandler) { return ReflectionTestUtils.getField(channelHandler.getChannelWriter(), "lifecycleState") .toString(); }
private Queue<?> getCommandBuffer(RedisChannelHandler<?, ?> channelHandler) { return (Queue<?>) ReflectionTestUtils.getField(channelHandler.getChannelWriter(), "commandBuffer"); }
private Queue<?> getQueue(RedisChannelHandler<?, ?> channelHandler) { return (Queue<?>) ReflectionTestUtils.getField(channelHandler.getChannelWriter(), "queue"); }