I have got a Grails 3.3.5 application with several Unit tests. While I run this tests individually they run as expected, but when I run a general test-app the tests fails with this message:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.grails.beans.ConstraintsEvaluator': Cannot resolve reference to bean 'grailsDomainClassMappingContext' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'grailsDatastore': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.datastore.mapping.simple.SimpleMapDatastore]: Constructor threw exception; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<?, ?>]
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:359)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:108)
at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:648)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:145)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at org.grails.testing.GrailsUnitTest$Trait$Helper.defineBeans(GrailsUnitTest.groovy:100)
at org.grails.testing.gorm.spock.DataTestSetupSpecInterceptor.setupDataTestBeans(DataTestSetupSpecInterceptor.groovy:50)
at org.grails.testing.gorm.spock.DataTestSetupSpecInterceptor.configureDataTest(DataTestSetupSpecInterceptor.groovy:85)
at org.grails.testing.gorm.spock.DataTestSetupSpecInterceptor.intercept(DataTestSetupSpecInterceptor.groovy:43)
at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:87)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.runTestClass(JUnitTestClassExecuter.java:114)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecuter.execute(JUnitTestClassExecuter.java:57)
at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassProcessor.processTestClass(JUnitTestClassProcessor.java:66)
at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:32)
at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:109)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:35)
at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:147)
at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:129)
at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:404)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'grailsDatastore': Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.datastore.mapping.simple.SimpleMapDatastore]: Constructor threw exception; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<?, ?>]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1197)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:372)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1177)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1071)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:312)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:308)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:351)
... 36 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.grails.datastore.mapping.simple.SimpleMapDatastore]: Constructor threw exception; nested exception is org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<?, ?>]
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:122)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:271)
... 54 more
Caused by: org.springframework.core.convert.ConverterNotFoundException: No converter found capable of converting from type [java.lang.String] to type [java.util.Map<?, ?>]
at org.springframework.core.convert.support.GenericConversionService.handleConverterNotFound(GenericConversionService.java:324)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:206)
at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:187)
at org.springframework.core.env.AbstractPropertyResolver.convertValueIfNecessary(AbstractPropertyResolver.java:266)
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:87)
at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:66)
at org.springframework.core.env.AbstractPropertyResolver.getProperty(AbstractPropertyResolver.java:169)
at org.springframework.core.env.AbstractEnvironment.getProperty(AbstractEnvironment.java:542)
at org.grails.datastore.mapping.core.connections.AbstractConnectionSources.getConnectionSourceNames(AbstractConnectionSources.groovy:52)
at org.grails.datastore.mapping.core.connections.InMemoryConnectionSources.<init>(InMemoryConnectionSources.groovy:24)
at org.grails.datastore.mapping.core.connections.ConnectionSourcesInitializer.create(ConnectionSourcesInitializer.groovy:28)
at org.grails.datastore.mapping.simple.SimpleMapDatastore.<init>(SimpleMapDatastore.java:117)
at org.grails.datastore.mapping.simple.SimpleMapDatastore.<init>(SimpleMapDatastore.java:178)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:142)
... 56 more
Here's one of the unit test that works as expected when runned individually but fails with the global test:
package my.package
import grails.testing.gorm.DomainUnitTest
import spock.lang.Specification
class CapituloSpec extends Specification implements DomainUnitTest<Capitulo> {
void "test id cannot be null"() {
when:
domain.id = null
then:
!domain.validate(['id'])
domain.errors['id'].code == 'nullable'
}
void "test titulo cannot be null or blank"() {
when:
domain.titulo = null
then:
!domain.validate(['titulo'])
domain.errors['titulo'].code == 'nullable'
when:
domain.titulo = ''
then:
!domain.validate(['titulo'])
domain.errors['titulo'].code == 'blank'
}
void "test titulo maxSize"() {
when: "titulo is 101 characters length"
domain.titulo = 'a' * 101
then: "titulo validation fails"
!domain.validate(['titulo'])
domain.errors['titulo'].code == 'maxSize.exceeded'
when: "titulo is 100 characters length"
domain.titulo = 'a' * 100
then: "titulo validation succeed"
domain.validate(['titulo'])
}
void "test capitulo ok"() {
when:
domain.id = 1
domain.titulo = "Test"
then:
domain.validate()
}
}
How can I solve this problems and run my tests together and not individually.
EDIT: I forgot to mention that I'm using two datasources, one default to save almost all the application data, and another one to save only 6 domains shared with another application.
Finally I've found a way to avoid the errors and run all the tests together. I must configure the datasource in all the tests using the doWithSpring closure.
First I made a Trait to configure the datasource using the applicationContext and the datasource name (if not given use the 'default' datasource):
package my.package
import groovy.transform.CompileStatic
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.core.convert.support.ConfigurableConversionService
import org.springframework.core.convert.converter.Converter
#CompileStatic
trait MultiDatasourceTest {
def configDatasource(ConfigurableApplicationContext applicationContext, String datasource = "default") {
System.setProperty("grails.gorm.connections", datasource)
ConfigurableConversionService conversionService = applicationContext.getEnvironment().getConversionService()
conversionService.addConverter(new StringToMapConverter())
}
}
class StringToMapConverter implements Converter<String, Map> {
#Override
Map convert(String source) {
source.split(",").collectEntries({
[(it):it]
})
}
}
Next I must add the trait to all my tests and call the configDatasource with the application context and the datasource name, if it's not the default one.
Default datasource:
package my.package
import grails.testing.gorm.DomainUnitTest
import org.springframework.context.ConfigurableApplicationContext
import spock.lang.Specification
class CapituloSpec extends Specification implements DomainUnitTest<Capitulo>, MultiDatasourceTest {
#Override
Closure doWithSpring() {
return {
configDatasource(application.mainContext as ConfigurableApplicationContext)
}
}
void "test id cannot be null"() {
when:
domain.id = null
then:
!domain.validate(['id'])
domain.errors['id'].code == 'nullable'
}
// More tests
}
Another datasource:
package my.package
import grails.testing.gorm.DomainUnitTest
import org.springframework.context.ConfigurableApplicationContext
import spock.lang.Specification
class DocumentoTeoSpec extends Specification implements DomainUnitTest<DocumentoTeo>, MultiDatasourceTest {
#Override
Closure doWithSpring() {
return {
configDatasource(application.mainContext as ConfigurableApplicationContext, "sede")
}
}
void "test numeroExpediente cannot be null or blank"() {
when:
domain.numeroExpediente = null
then:
!domain.validate(['numeroExpediente'])
domain.errors['numeroExpediente'].code == 'nullable'
when:
domain.numeroExpediente = ''
then:
!domain.validate(['numeroExpediente'])
domain.errors['numeroExpediente'].code == 'blank'
when: "numeroExpediente is 21 characters long"
domain.numeroExpediente = 'a' * 21
then: "numeroExpediente validation fails"
!domain.validate(['numeroExpediente'])
domain.errors['numeroExpediente'].code == 'maxSize.exceeded'
when: "numeroExpediente is 20 characters long"
domain.numeroExpediente = 'a' * 20
then: "numeroExpediente validation succeed"
domain.validate(['numeroExpediente'])
}
// More tests
}
Related
Trying to update a small experimental Spring Elasticsearch project to reflect changes in the 3.2.6 release reference guide.
As noted: TransportClient is deprecated as of Elasticsearch 7 and will be removed in 8. Trying to reconfig to High Level Rest Client.
But getting the following errors
Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'elasticDatasource' defined in file [/Users/erichuang/Desktop/JE/00-Development/dev/lab/lab-elastic-search/lab-elastic-search/target/classes/com/elastic/labelasticsearch/config/ElasticDatasource.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carElasticRepo': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.ElasticsearchException: Error while for indexExists request: org.elasticsearch.action.admin.indices.get.GetIndexRequest#b5d8ebb
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
com.elastic.labelasticsearch.LabElasticSearchApplication.main(LabElasticSearchApplication.java:15)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carElasticRepo': Invocation of init method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.elasticsearch.repository.support.SimpleElasticsearchRepository]: Constructor threw exception; nested exception is org.springframework.data.elasticsearch.ElasticsearchException: Error while for indexExists request: org.elasticsearch.action.admin.indices.get.GetIndexRequest#b5d8ebb
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1796)
... 24 common frames omitted
Caused by: java.net.UnknownHostException: localhost/<unresolved>: nodename nor servname provided, or not known
at java.base/java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.base/java.net.InetAddress$PlatformNameService.lookupAllHostAddr(InetAddress.java:932)
at java.base/java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1505)
at java.base/java.net.InetAddress$NameServiceAddresses.get(InetAddress.java:851)
at java.base/java.net.InetAddress.getAllByName0(InetAddress.java:1495)
at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1354)
at java.base/java.net.InetAddress.getAllByName(InetAddress.java:1288)
...
... 63 common frames omitted
Old setup (works)
ElasticSearchConfig
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.elastic.labelasticsearch.repo")
public class ElasticSearchConfig {
private static final String esHost = "localhost";
private static final int esPort = 9300;
#Bean
public Client client() throws UnknownHostException {
var transportClient = new PreBuiltTransportClient(Settings.EMPTY);
transportClient.addTransportAddress(new TransportAddress(InetAddress.getByName(esHost), esPort));
return transportClient;
}
#Bean(name ={"elasticsearchOperations", "elasticsearchTemplate"})
public ElasticsearchOperations esTemplate() throws UnknownHostException {
return new ElasticsearchTemplate(client());
}
#Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
New Setup
#Configuration
#EnableElasticsearchRepositories(basePackages = "com.elastic.labelasticsearch.repo")
public class RestClientConfig extends AbstractElasticsearchConfiguration {
#Override
#Bean
public RestHighLevelClient elasticsearchClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("localhost:9300")
.build();
return RestClients.create(clientConfiguration).rest();
}
}
What am I missing?
This is a bug resulting from as change in Java 14 in the java.net.InetSocketAddress.toString() method. This has been fixed in 4.0.RC2 (released yesterday).
Edit: I will backport this into the 3.2 branch as well
You will need to configure your bean using this way that allow to separate the host port and http protocol used:
#Configuration
#EnableElasticsearchRepositories(basePackages = "*")
public class ElasticsearchClientConfig {
#Value("${elasticsearch.host}")
private String host;
#Value("${elasticsearch.port}")
private int port;
#Value("${elasticsearch.protocol}")
private String protocol;
#Value("${elasticsearch.username}")
private String userName;
#Value("${elasticsearch.password}")
private String password;
#Bean(destroyMethod = "close")
public RestHighLevelClient restClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, protocol)).setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
I'm using:
Spring-data-neo4j 4.2.0-SNAPSHOT (tried with 4.2.0.RC1 too)
and since the DATAGRAPH-939 commit, I'm not able to work with repositories anymore.
#Repository
public interface MyEventRepository extends GraphRepository<Event> {}
The error:
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myEventRepository': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749)
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:189)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1148)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1050)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:735)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'java.lang.Class<org.springframework.data.repository.Repository<?, ?>>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1466)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1097)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1059)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
... 41 common frames omitted
Here is an example of my failing test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = { SimpleTest.TestConfiguration.class })
public class SimpleTest {
#Configuration
#EnableNeo4jRepositories("com.nagra.ml.sp.cpm.core.repositories.test")
public static class TestConfiguration {
#Bean
public org.neo4j.ogm.config.Configuration configuration() {
org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();
config .driverConfiguration()
.setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver");
return config;
}
#Bean
public SessionFactory sessionFactory() {
return new SessionFactory(configuration(), "com.nagra.ml.sp.cpm.model");
}
#Bean
public Neo4jTransactionManager transactionManager() {
return new Neo4jTransactionManager(sessionFactory());
}
}
#Test
public void test() {
assertTrue(true);
}
}
According to documentation, the way of declaring repositories seems to be correct, am I doing something wrong ?
Thanks
I no longer have issues with repositories. I'm now using SDN 4.2.0.RELEASE with Spring boot 1.5.1 and I no longer extends GraphRepository as explained in SDN4.2.0 documentation.
import grails.test.mixin.integration.Integration
import spock.lang.Specification
#Integration
class MySpec extends Specification {
def setup() {
}
def cleanup() {
}
void "test something"() {
expect:"tests a"
true
}
}
MySpec > test something FAILED
java.lang.IllegalStateException
Caused by: org.springframework.beans.factory.BeanCreationException
Caused by: org.springframework.beans.factory.BeanCreationException
Caused by: org.springframework.beans.factory.BeanCreationException
Caused by: java.lang.NullPointerException
1 test completed, 1 failed
:integrationTest FAILED
:mergeTestReports
I run
"test-app -integration MySpec" command
Is that an error in grails or I do smth wrong?
UPDATE!
I found a solution - just add
testCompile "org.grails.plugins:hibernate"
to build.gradle
Testing was never so easy and intuitive before the use of Spock.We can always test the exceptions in grails Spock Testing. For example we have a method which throws exception like :
String getUserType(int age){
if(age<=0){
throw new MyException("Invalid age")
}else if( age>0 && age<50){
return "Young"
}else{
return "Old"
}
}
Now we will write the test case of this method for checking whether exception is thrown for invalid inputs or not.
def "exception should be thrown only for age less than or equal to 0"{
given:
String type = getUserType(34)
expect:
type == "Young"
notThrown MyException
when:
type = getUserType(0)
then:
thrown MyException
}
This is how we have tested whether exception is thrown for invalid input or not.
Hope it helps
I'm trying to get the Fixtures plugin working for my unit tests but every time I make it load data, I always get a BeanCreationException.
Here's how the setup method in my Spec looks like:
def fixtureLoader = new FixtureLoader(grailsApplication)
def setup() {
fixtureLoader.load {
person(Person, firstName: 'Juan', lastName: 'dela Cruz')
}
}
Every time I run any test I get:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'person': Initialization of bean failed; nested exception is java.lang.NullPointerException: Cannot invoke method getDomainClass() on null object
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:547)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:703)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.codehaus.groovy.grails.commons.spring.DefaultRuntimeSpringConfiguration.getApplicationContext(DefaultRuntimeSpringConfiguration.java:156)
at grails.spring.BeanBuilder.createApplicationContext(BeanBuilder.java:593)
at grails.plugin.fixtures.builder.FixtureBuilder.createApplicationContext(FixtureBuilder.groovy:140)
at grails.plugin.fixtures.Fixture.load(Fixture.groovy:43)
at grails.plugin.fixtures.FixtureLoader.load(FixtureLoader.groovy:50)
at demo.SampleSpec.setup(SampleSpec.groovy:16)
Caused by: java.lang.NullPointerException: Cannot invoke method getDomainClass() on null object
at grails.plugin.fixtures.builder.processor.FixtureBeanPostProcessor.getDomainClass(FixtureBeanPostProcessor.groovy:136)
at grails.plugin.fixtures.builder.processor.FixtureBeanPostProcessor.postProcessAfterInitialization(FixtureBeanPostProcessor.groovy:40)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:421)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1558)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
... 14 more
I am in the process of upgrading an app from Grails 1.3.9 to Grails 2.2.1. When I issue the run-app command, I get a long stacktrace that begins with this error and then more or less repeats it for about 400 lines:
2013-03-07 13:32:11.364 ERROR [ StackTrace] Full Stack Trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManagerPostProcessor': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager': Cannot resolve reference to bean 'sessionFactory' while setting bean property 'sessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory': Invocation of init method failed; nested exception is org.hibernate.MappingException: property [sponsoringManager] not found on entity [com.mycompany.myapp.ManagerDelegate]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
at org.codehaus.groovy.grails.commons.spring.ReloadAwareAutowireCapableBeanFactory.doCreateBean(ReloadAwareAutowireCapableBeanFactory.java:118)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.registerBeanPostProcessors(AbstractApplicationContext.java:713)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:457)
at org.codehaus.groovy.grails.commons.spring.DefaultRuntimeSpringConfiguration.getApplicationContext(DefaultRuntimeSpringConfiguration.java:153)
at org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator.configure(GrailsRuntimeConfigurator.java:170)
at org.codehaus.groovy.grails.commons.spring.GrailsRuntimeConfigurator.configure(GrailsRuntimeConfigurator.java:127)
at org.codehaus.groovy.grails.web.context.GrailsConfigUtils.configureWebApplicationContext(GrailsConfigUtils.java:121)
at org.codehaus.groovy.grails.web.context.GrailsContextLoader.initWebApplicationContext(GrailsContextLoader.java:107)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4791)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5285)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
I think the pertinent part is this:
org.hibernate.MappingException: property [sponsoringManager] not found on entity [com.mycompany.myapp.ManagerDelegate]
Here's the code for the ManagerDelegate domain class, which is a many to many join class:
package com.mycompany.myapp
class ManagerDelegate extends Base implements Serializable {
static belongsTo = [sponsoringManager:User, delegate:User]
boolean equals(other) {
if (!(other instanceof ManagerDelegate)) {
return false
}
other.sponsoringManager.id == sponsoringManager.id && other.delegate.id == delegate.id
}
static mapping = {
id composite: [
'sponsoringManager',
'delegate'
]
version false
}
}
As you can see, ManagerDelegate does contain a sponsoringManager property which is declared in the belongsTo statement. This worked perfectly in Grails 1.3.9.
Here is the User class:
class User {
static hasMany = [sponsoringManagers: ManagerDelegate, delegates: ManagerDelegate]
static mappedBy = [sponsoringManagers: "delegate", delegates: "sponsoringManager"]
static mapping = {
id generator: 'uuid'
sponsoringManagers cascade: 'all-delete-orphan'
delegates cascade: 'all-delete-orphan'
}
...
}
When I try to access the app from my browser, nothing is displayed and no log output is produced.