Integration test with DBUnit IO Exception Java - java

I write an integration test on a SpringFramework Controller but i have some issues with data base. I do not undertand why dbunit can not locate my schema.sql file. I tried to use absolute path but it did not work too.
ControllerTest
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class })
#DatabaseSetup(value = "login.xml")
public class LoginControllerTest {
private MockMvc mockMvc;
private static final String JDBC_DRIVER = org.h2.Driver.class.getName();
private static final String JDBC_URL = "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1";
private static final String SCHEMA_PATH = "schema.sql";
private static final String USER = "sa";
private static final String PASSWORD = "";
#BeforeClass
public static void createSchema() throws Exception {
RunScript.execute(JDBC_URL, USER, PASSWORD, SCHEMA_PATH, null, false);
}
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.xmlConfigSetup("loginControllerTest-context.xml").build();
IDataSet dataSet = readDataSet();
cleanlyInsert(dataSet);
}
private IDataSet readDataSet() throws Exception {
return new FlatXmlDataSetBuilder().build(new File("login.xml"));
}
private void cleanlyInsert(IDataSet dataSet) throws Exception {
IDatabaseTester databaseTester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD);
databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
databaseTester.setDataSet(dataSet);
databaseTester.onSetup();
}
#Test
#ExpectedDatabase("login.xml")
public void testShowForm() throws Exception {
mockMvc.perform(get("/login")).andExpect(status().isOk()).andExpect(view().name("/login"))
.andExpect(forwardedUrl("/WebContent/j/login.jsp"))
.andExpect(model().attribute("form", hasProperty("od", nullValue())))
.andExpect(model().attribute("form", hasProperty("email", isEmptyOrNullString())))
.andExpect(model().attribute("form", hasProperty("username", isEmptyOrNullString())))
.andExpect(model().attribute("form", hasProperty("hostname", isEmptyOrNullString())))
.andExpect(model().attribute("form", hasProperty("pass", isEmptyOrNullString())));
}
}
loginControllerTest-context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<tx:annotation-driven transaction-manager="transactionManager" />
<context:component-scan base-package="com.profiles.controller.test" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.jdbcx.JdbcDataSource" />
<property name="url" value="jdbc:hsqldb:mem:login" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
</beans>
Stack Trace
org.h2.message.DbException: IO Exception: "java.io.FileNotFoundException: schema.sql (The system cannot find the file specified)"; "schema.sql" [90031-191]
at org.h2.message.DbException.get(DbException.java:168)
at org.h2.message.DbException.convertIOException(DbException.java:330)
at org.h2.tools.RunScript.process(RunScript.java:333)
at org.h2.tools.RunScript.execute(RunScript.java:303)
at com.profiles.controller.test.LoginControllerTest.createSchema(LoginControllerTest.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.internal.runners.ClassRoadie.runBefores(ClassRoadie.java:49)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:36)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.h2.jdbc.JdbcSQLException: IO Exception: "java.io.FileNotFoundException: schema.sql (The system cannot find the file specified)"; "schema.sql" [90031-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
... 18 more
Caused by: java.io.FileNotFoundException: schema.sql (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at org.h2.store.fs.FilePathDisk.newInputStream(FilePathDisk.java:321)
at org.h2.store.fs.FileUtils.newInputStream(FileUtils.java:218)
at org.h2.tools.RunScript.process(RunScript.java:185)
at org.h2.tools.RunScript.process(RunScript.java:328)
... 15 more
SOLUTION
i have fix my problem when i move sql file to a folder under test source folder and set the path to - classpath:/sql/schema.sql

Related

Couldn't pass the #bean value to another class through Autowiring

I am new to spring. So I couldn't figure out what issue is there in the below code. I have two classes. I am defining a #Bean Channel and am autowiring that bean in the next class. I am using annotation for autowiring. When I try " System.out.println(externalChannel.toString());" am getting null values and the exception null pointer exception is thrown.
#Configuration
public class MessagingConfig
{
#Value("${service.name}")
private String queueName; // NOSONAR
#Value("${${user}")
private String schema;
#Value("${Owner}")
private String owner;
#Bean
public Channel externalChannel()
{
EventsProvider eventsProvider = new EventsProvider();
eventsProvider.setOwner(owner);
System.out.println("-------Cost And Events Channel-------"+eventsProvider.getEventsChannel());
return eventsProvider.getEventsChannel();
}
}
And Another class is
#Component
#LoggedService
#Monitored(useActualType = true)
public class MessagePublish {
#Autowired
private MessagingService messageService;
#Autowired
private Channel externalChannel;
public void publishTPSMessage(SourceTransaction sourceTransaction)
{
TPSEvent event = new TPSEvent(ContextHolder.getContextId(), new Date(), GuidUtils.generateGuid(),sourceTransaction);
Message<TPSEvent> message = new Message<TPSEvent>(event);
message.getHeader().setMessageType(TPSEvent.class.getName());
message.getHeader().setPayloadEncodingType(SystemCodecs.XML.name());
System.out.println(message.toString());
System.out.println(externalChannel.toString());
messageService.publish(externalChannel, message);
}
}
More Info
public Channel getEventsChannel() {
return Channel.builder()
.setName("necessarySources")
.setConnectionName("defaultConnection")
.setType(ChannelType.Topic)
.setConnectionData(AqSqlConnectionData.buildString(this.owner, "Safi"))
.setSubscriberNames(new String[]{"Safi_Autowire"})
.build();
}
Main Class
public class TPSHandler {
public static void main(String[] args) {
BatchExport batchExportBean=getBatchExportASJAXBElement();
System.out.println(" batchExportBean Trans Description : " + batchExportBean.getDueDate());
for(Pay pay :batchExportBean.getPay()) {
SourceTransaction sourceTransaction=mapPayBatchToSourceTransaction(pay,batchExportBean);
String sourceTraString = getSourceTransactionASXML(sourceTransaction);
System.out.println(" sourceTraString : \n" + sourceTraString);
MessagePublish messagePublish= new MessagePublish();
//SourceTransaction sourceTransaction= new SourceTransaction();
messagePublish.publishTPSMessage(sourceTransaction);
}
}
}
My Servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:jaxws="http://cxf.apache.org/jaxws" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.xsd
http://cxf.apache.org/jaxrs
http://cxf.apache.org/schemas/jaxrs.xsd">
<import resource="classpath:config-properties.xml" />
<import resource="classpath:datasource.xml" />
<import resource="classpath:transaction-manager.xml" />
<import resource="classpath:jmx.xml" />
<context:component-scan base-package="com.imosAdapter" />
<bean class="com.oasis.services.messaging.config.MessagingServicesConfig" />
<bean class="com.oasis.services.messaging.config.DefaultMessagingConnectorsConfig" />
<bean class="com.oasis.services.messaging.config.LoaderConfig" />
<context:annotation-config />
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>/config/oasis-component.properties</value>
</property>
</bean>
</beans>
The exception thrown:
Exception in thread "main" java.lang.NullPointerException
at com.imosAdapter.tps.events.MessagePublish.publishTPSMessage(MessagePublish.java:46)
at com.imosAdapter.tps.TPSHandler.main(TPSHandler.java:64)
What is the issue over here? Can anybody help me with this? what exactly I am missing here?
You need to initialize a Spring context at the start of your application when you do not create a servlet / run as a Server.
See Using Spring in a standalone application

Neo4j with Spring: No bean named 'getSessionFactory' available

I'm new to neo4j and spring in combination and spring at all. When I start debugging, I get the following exception:
Exception in thread "main"
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'getSessionFactory' available
Can anyone help me please?
apllication-context.xml:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="de.unileipzig.analyzewikipedia.neo4j" />
<!--neo4j:config storeDirectory="C:/temp/neo4jdatabase" base-package="de.unileipzig.analyzewikipedia.neo4j.dataobjects"/-->
<neo4j:repositories base-package="de.unileipzig.analyzewikipedia.neo4j.repositories"/>
<tx:annotation-driven />
<bean id="graphDatabaseService" class="org.springframework.data.neo4j.support.GraphDatabaseServiceFactoryBean"
destroy-method="shutdown" scope="singleton">
<constructor-arg value="C:/develop/uni/analyze-wikipedia-netbeans/database"/>
<constructor-arg>
<map>
<entry key="allow_store_upgrade" value="true"/>
</map>
</constructor-arg>
</bean>
</beans>
Startup-Class
package de.unileipzig.analyzewikipedia.neo4j.console;
import de.unileipzig.analyzewikipedia.neo4j.dataobjects.Article;
import de.unileipzig.analyzewikipedia.neo4j.service.ArticleService;
import java.io.File;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Neo4JConsole {
/**
* MAIN: start the java file
*
* #param args as string array
*/
public static void main(String[] args) {
String cwd = (new File(".")).getAbsolutePath();
ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
ArticleService service = (ArticleService) context.getBean("articleService");
Article art = createArticle();
createArticle(service, art);
System.out.println("Article created");
}
private static Article createArticle() {
Article article = new Article();
article.setTitle("Title");
return article;
}
private static Article createArticle(ArticleService service, Article art) {
return service.create(art);
}
}
Thank you.
Do you have this configuration?
#Configuration
#EnableNeo4jRepositories("org.neo4j.cineasts.repository")
#EnableTransactionManagement
#ComponentScan("org.neo4j.cineasts")
public class PersistenceContext extends Neo4jConfiguration {
#Override
public SessionFactory getSessionFactory() {
return new SessionFactory("org.neo4j.cineasts.domain");
}
}
For more information, try to look here

SpringFramework and DbUnit integration test class not found AnnotationBeanConfigurerAspect Java

I write this integration test but i can not handle the exceptions. The stack trace shows me that the applicationContext can not be found and AnnotationBeanConfigurerAspect.class can not be found.
TestController
#RunWith(SpringJUnit4ClassRunner.class)
#WebAppConfiguration
#ContextConfiguration(locations = { "file:test/test/loginController/LoginControllerTest2-context.xml" })
#TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class, DbUnitTestExecutionListener.class })
#DatabaseSetup("login.xml")
public class LoginControllerTest2 {
private static final String JDBC_DRIVER = "org.h2.Driver";
private static final String JDBC_URL = "jdbc:h2:mem:login;DB_CLOSE_DELAY=-1";
private static final String USER = "sa";
private static final String PASS = "";
private static final String SCHEMA_FILE = "h2.sql";
private static final String DATASET = "login.xml";
private MockMvc mockMvc;
#Resource
private WebApplicationContext wac;
#BeforeClass
public static void createSchema() throws ClassNotFoundException {
Class.forName(JDBC_DRIVER);
try {
Connection conn = dataSource().getConnection();
InputStreamReader in = new InputStreamReader(LoginControllerTest2.class.getResourceAsStream(SCHEMA_FILE));
RunScript.execute(conn, in);
} catch (Exception e) {
// TODO: handle exception
}
}
#Before
public void loadTestData() throws Exception {
// mockMvc =
// MockMvcBuilders.xmlConfigSetup("classpath:LoginControllerTest2-context.xml").build();
mockMvc = MockMvcBuilders.webApplicationContextSetup(wac).build();
// mockMvc =
// MockMvcBuilders.annotationConfigSetup(LoginControllerTest2.class).build();
IDataSet ids = new FlatXmlDataSetBuilder().build(LoginControllerTest2.class.getResourceAsStream(DATASET));
JdbcDatabaseTester databaseTester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASS);
databaseTester.setSetUpOperation(org.dbunit.operation.DatabaseOperation.CLEAN_INSERT);
databaseTester.setDataSet(ids);
databaseTester.onSetup();
}
private static DataSource dataSource() {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL(JDBC_URL);
dataSource.setUser(USER);
dataSource.setPassword(PASS);
return dataSource;
}
#Test
#ExpectedDatabase("login.xml")
public void testShowForm() throws Exception {
mockMvc.perform(get("/login")).andExpect(status().isOk()).andExpect(view().name("/login"))
.andExpect(forwardedUrl("../../WebContent/j/login.jsp"))
.andExpect(model().attribute("form", hasProperty("passportId", nullValue())))
.andExpect(model().attribute("form", hasProperty("email", isEmptyOrNullString())))
.andExpect(model().attribute("form", hasProperty("username", isEmptyOrNullString())))
.andExpect(model().attribute("form", hasProperty("hostname", isEmptyOrNullString())))
.andExpect(model().attribute("form", hasProperty("pass", isEmptyOrNullString())));
}
}
application context
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="test.loginController" />
<context:annotation-config />
<mvc:annotation-driven />
<context:spring-configured />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
<constructor-arg>
<bean class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driverClass" value="org.h2.Driver" />
<property name="url"
value="jdbc:h2:mem:login;DB_CLOSE_DELAY=-1;TRACE_LEVEL_SYSTEM_OUT=2;TRACE_LEVEL_FILE=4" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>
</constructor-arg>
</bean>
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="test/test/loginController/h2.sql" />
</jdbc:initialize-database>
</beans>
stack trace
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:94)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:72)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:200)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:259)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:261)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:219)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect] for bean with name 'org.springframework.context.config.internalBeanConfigurerAspect' defined in null; nested exception is java.lang.ClassNotFoundException: org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect
Related cause: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect] for bean with name 'org.springframework.context.config.internalBeanConfigurerAspect' defined in null; nested exception is java.lang.ClassNotFoundException: org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:133)
at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:109)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:68)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:86)
... 26 more
Caused by: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect] for bean with name 'org.springframework.context.config.internalBeanConfigurerAspect' defined in null; nested exception is java.lang.ClassNotFoundException: org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1328)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getTypeForFactoryMethod(AbstractAutowireCapableBeanFactory.java:665)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.determineTargetType(AbstractAutowireCapableBeanFactory.java:621)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:591)
at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1397)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doGetBeanNamesForType(DefaultListableBeanFactory.java:434)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:412)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanNamesForType(DefaultListableBeanFactory.java:398)
at org.springframework.context.support.AbstractApplicationContext.getBeanNamesForType(AbstractApplicationContext.java:1040)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.initHandlerMethods(AbstractHandlerMethodMapping.java:139)
at org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.afterPropertiesSet(AbstractHandlerMethodMapping.java:123)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.afterPropertiesSet(RequestMappingHandlerMapping.java:126)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
... 41 more
Caused by: java.lang.ClassNotFoundException: org.springframework.beans.factory.aspectj.AnnotationBeanConfigurerAspect
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at org.springframework.util.ClassUtils.forName(ClassUtils.java:249)
at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:395)
at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1349)
at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1320)
... 54 more
Looks like you miss the spring-aspects.jar as a dependency in your Project.
Add to your pom:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>
Try to add this spring-aspects dependency like this:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
</dependency>

Concurrent testing with TestNG and Spring Transaction

I have a service class, the service class is annotated with #Transactional(propagation = Propagation.REQUIRES_NEW) and its public method is defined in an interface:
public interface UniqueKeyGeneratorService {
void initializeUniqueKeys(Entity entity);
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
public final class KeyGeneratorServiceImpl implements UniqueKeyGeneratorService, DisposableBean {
private final UniqueKeyGeneratorStrategy strategy;
private KeyGeneratorServiceImpl(final UniqueKeyGeneratorStrategy strategy) {
this.strategy = strategy;
}
#Override
public void initializeUniqueKeys(final Entity entity) {
// ... the business logic
}
// ... some private methods
#Override
public void destroy() {
strategy.destroy();
}
}
And the bean is created using a FactoryBean (to initialize the strategy).
I want to test the service, so I configured an embedded H2 database, defined a connection pool using Apache Commons DBCP and write proper test code as:
#ContextConfiguration("/path/to/xml/config/file.xml")
#Transactional
public class TestUniqueKeyGeneratorService extends AbstractTransactionalTestNGSpringContextTests {
#Autowired
private UniqueKeyGeneratorService service;
#Test
#Rollback(false)
public void testCodeGeneration() {
final Department department1 = new Department();
department1.setName("Abcd");
service.initializeUniqueKeys(department1);
final String code = department1.getCode();
Assert.assertNotNull(code);
}
// ... some more test methods
}
and have
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.h2.Driver"/>
<property name="url" value="jdbc:h2:mem:db1"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven/>
<bean id="uniqueKeyGeneratorService"
class="com.mycompany.uniquekey.UniqueKeyGeneratorServiceFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
the test passes, but when I change the #Test annotation to #Test(invocationCount = 10, singleThreaded = false, threadPoolSize = 2) following exception occures:
org.springframework.transaction.CannotCreateTransactionException: Could not open JDBC Connection for transaction; nested exception is java.sql.SQLException: Connection is closed.
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:240) ~[org.springframework.jdbc-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:371) ~[org.springframework.transaction-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.startTransaction(TransactionalTestExecutionListener.java:514) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.startNewTransaction(TransactionalTestExecutionListener.java:272) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.beforeTestMethod(TransactionalTestExecutionListener.java:165) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:358) ~[org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at org.springframework.test.context.testng.AbstractTestNGSpringContextTests.springTestContextBeforeTestMethod(AbstractTestNGSpringContextTests.java:146) [org.springframework.test-3.1.3.RELEASE.jar:3.1.3.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.6.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) ~[na:1.6.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_31]
at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_31]
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:80) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:564) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:213) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeMethod(Invoker.java:653) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111) [org.testng-6.8.jar:6.8-201210030754]
at org.testng.internal.thread.ThreadUtil$2.call(ThreadUtil.java:64) [org.testng-6.8.jar:6.8-201210030754]
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) [na:1.6.0_31]
at java.util.concurrent.FutureTask.run(FutureTask.java:138) [na:1.6.0_31]
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) [na:1.6.0_31]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) [na:1.6.0_31]
at java.lang.Thread.run(Thread.java:662) [na:1.6.0_31]
Caused by: java.sql.SQLException: Connection is closed.
at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.checkOpen(PoolingDataSource.java:185) ~[org.apache.commons-dbcp-1.4.jar:1.4]
at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.getAutoCommit(PoolingDataSource.java:234) ~[org.apache.commons-dbcp-1.4.jar:1.4]
at org.springframework.jdbc.datasource.DataSourceTransactionManager.doBegin(DataSourceTransactionManager.java:218) ~[org.springframework.jdbc-3.1.3.RELEASE.jar:3.1.3.RELEASE]
... 24 common frames omitted
any idea how to handle this exception?
p.s. I reviewed H2 documentations, and it supports multiple connections in embedded mode.
The answer is located in TestNG multithreaded test with Spring #Transactional

Spring autowire issue

i am running a unit tests and uses a Service class to perform some business logic. however, the unit tests fails saying that the service class is null dispite setting up the Autorwire annotations for it.
below is my unit test:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/FreedomSpring-servlet.xml" })
public class UserControllerTest
{
private UserController controller;
#Inject
private ApplicationContext applicationContext;
private String jsonUser = "{ \"username\":\"jonneymendoza\",\"emailAddress\":\"jon#google.com\", \"password\":\"12345678\",\"firstName\":\"jono\", \"surname\":\"richy\", \"country\":\"united kingdom\",\"bio\":\"Bio stuff goes here about the user. where he comes from etc etc. all is well. lets go go go\" }";
#Before
public void setup()
{
controller = new UserController();
assertNotNull(applicationContext);
}
#Test
public void testCreateNewAccount()
{
ResponseEntity<String> response = controller
.createNewAccount(new HttpEntity<String>(jsonUser));
assertEquals(HttpStatus.CREATED, response.getStatusCode());
}
}
Here is the controller i am testing
#Controller
public class UserController
{
#Autowired
private UserService userService;
#RequestMapping(value = "/user", method = RequestMethod.PUT, consumes = "application/json")
public ResponseEntity<String>createNewAccount(HttpEntity<String>request)
{
userService.registerNewUser( JSONObject.fromObject(request.getBody())); //fails here
return new ResponseEntity<String>(null, responseHeaders, HttpStatus.CREATED);
}
}
The service class:
#Service("UserService")
#Transactional
public class UserService implements UserServiceInterface
{
#Override
public void registerNewUser(JSONObject user) throws InvalidDataException, JSONException
{
// parse json object to a User object
User newUser = parseJsonObject(user);
UserDao userDao = new UserDao();
userDao.addNewUser(newUser);
}
}
My service-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config />
<!-- Define services here -->
<bean id="UserService" class="com.jr.freedom.user.UserService"></bean>
</beans>
My servlett:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>database.properties</value>
</list>
</property>
</bean>
<import resource="mvc-config.xml" />
<import resource="service-config.xml" />
<import resource="classpath:datasource-config.xml" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<context:component-scan base-package="com.jr.freedom.controllers"></context:component-scan>
</beans>
And finally the error i recieve
java.lang.NullPointerException
at com.jr.freedom.controllers.UserController.createNewAccount(UserController.java:56)
at com.jr.freedom.controllers.UserControllerTest.testCreateNewAccount(UserControllerTest.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
You need to inject (with some annotation) or retreive userController from the applicationContext so that Spring magic (i.e. injection or userService in your case) works.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/FreedomSpring-servlet.xml" })
public class UserControllerTest {
#Autowired
private UserController userController;
#Inject
private ApplicationContext applicationContext;
private String jsonUser = "{ \"username\":\"jonneymendoza\",\"emailAddress\":\"jon#google.com\", \"password\":\"12345678\",\"firstName\":\"jono\", \"surname\":\"richy\", \"country\":\"united kingdom\",\"bio\":\"Bio stuff goes here about the user. where he comes from etc etc. all is well. lets go go go\" }";
#Before
public void setup() {
assertNotNull(applicationContext);
assertNotNull(userController);
}

Categories