SpringFramework and DbUnit integration test class not found AnnotationBeanConfigurerAspect Java - 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>

Related

Integration test with DBUnit IO Exception 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

Spring with RabbitMq and Apache Commons Config: Constructor threw exception; nested exception is java.lang.NullPointerException

I'm simply trying to autowire the following rabbitmq consumer:
#Component
public class SmsQueueConsumer {
//NOT SURE IF/ WHY THE CONFIG IS NULL...
#Autowired
Configuration config;
public SmsQueueConsumer() throws Exception {
//THIS IS WHERE THE NULL POINTER OCCURS (stack trace refers to line 54)
String rabbitMqHost = config.getString("rabbitMq.hostName");
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(rabbitMqHost);
com.rabbitmq.client.Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(queueName, false, false, false, null);
Consumer consumer = new DefaultConsumer(channel) {
#Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
//... handle deliv logic
};
}
}
The above class is autowired in the service implementation class:
#Service
public class ServiceImpl implements Service {
//HERE IS THE ABOVE CLASS BEING AUTOWIRED
#Autowired(required=true)
private SmsQueueConsumer queueConsumer;
//NOTE THAT I ALSO AUTOWIRE THE CONFIG HERE TOO!
#Autowired(required=true)
private Configuration config;
#Override
public ServiceResponse doStuff(MyCoObj obj) throws Exception
{
//...
queueSmsMessage(simpleMessage);
//...
}
private void queueSmsMessage(SimpleSmsMessage simpleSmsMessage) {
String rabbitMqHostName = config.getString("rabbitMq.hostName");
String smsQueueName = config.getString("auctions.sms.queue.name");
Gson gson = new Gson();
String smsMessageJson = gson.toJson(simpleSmsMessage);
try {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(rabbitMqHostName);
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(smsQueueName, false, false, false, null);
channel.basicPublish("", smsQueueName, null, smsMessageJson.getBytes());
channel.close();
connection.close();
} catch (Exception e) {
logger.warn("sms message could not be queued. TODO retry"); // TODO
}
}
}
I've set up a testApplicationContext to include the beans needed
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-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/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<context:component-scan base-package="com.myCompany.basePackageToScan" />
<context:annotation-config />
<bean id="config" class="org.apache.commons.configuration.PropertiesConfiguration">
<constructor-arg value = "some.properties"/>
</bean>
<bean id="smsQueueConsumer" class="com.myCompany.basePackageToScSmsQueueConsumer" />
</beans>
When I run the test, I get the following stack trace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'smsQueueConsumer' defined in class path resource [testApplicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.myCompany.basePackageToScan.SmsQueueConsumer]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1101)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
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.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.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)
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:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
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.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:68)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
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)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.myCompany.basePackageToScan.SmsQueueConsumer]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1094)
... 43 more
Caused by: java.lang.NullPointerException
at com.myCompany.basePackageToScan.SmsQueueConsumer.<init>(SmsQueueConsumer.java:54)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
... 45 more
This is the same stack trace I get when I run the app in Tomcat 7.
Please let me know if there's any other details I need to provide.
EDIT---
I believe that the problem may have to do with the way RabbitMq initiates a consumer... It sits there waiting for messages. Perhaps Spring cannot Autowire this class?
EDIT 2---
Removing the Configuration autowire and adding hard-coded settings in the SmsQueueConsumer for rabbitMqHost works... Now why won't the values pulled from the config work?
Ok, it's a bit hacky feeling, but what I did was instead of using the default constructor, I added the Configuration class as the argument to the constructor.
#Component
public class SmsQueueConsumer {
//I removed the autowiring of the config
//#Autowired
//Configuration config;
//and placed the config as an arg to the constructor
public SmsQueueConsumer(Configuration config) throws Exception {
//THIS IS WHERE THE NULL POINTER OCCURS (stack trace refers to line 54)
String rabbitMqHost = config.getString("rabbitMq.hostName");
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(rabbitMqHost);
com.rabbitmq.client.Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(queueName, false, false, false, null);
Consumer consumer = new DefaultConsumer(channel) {
#Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
//... handle deliv logic
};
}
}
Then I created a bean in the applicationContext.xml that injects the Configuration.
<bean id="config" class="org.apache.commons.configuration.PropertiesConfiguration">
<constructor-arg value = "some.properties"/>
</bean>
<bean id="bidsSmsQueueConsumer" class="com.myCompany.basePackage.SmsQueueConsumer">
<constructor-arg ref = "config" />
</bean>

NoSuchBeanDefinitionException occurring while running junit tests

Here's the setup:
I'm unit testing an email notification service that I wrote using Java Mail shown here:
#Service
public class EmailNotificationService implements NotificationService {
#Autowired
private CertificateService service;
#Override
public boolean sendFeedback(String title, String feedback) throws NotificationException {
// Code here
}
#Override
public boolean sendQuestion(String title, String question) throws NotificationException {
// Code here
}
}
My unit test class is as such:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration({"file:/service-commons/src/test/resources/service-commons.xml",
"file:/service-commons/src/test/resources/securityContext.xml",
"file:/service-commons/src/test/resources/mockUserProviderContext.xml" })
public class TestEmailNotificationService extends TestCase {
#Autowired
private EmailNotificationService emailServ;
#Resource
private WebApplicationContext context;
#Test
public void testSendFeedback() {
try {
boolean bool = emailServ.sendFeedback("feedbackTitle", "someFeedback");
assertTrue(bool);
} catch (NotificationException e) {
e.printStackTrace();
fail();
}
}
#Test
public void testSendQuestion() {
try {
boolean bool = emailServ.sendQuestion("questionTitle", "someQuestion");
assertTrue(bool);
} catch (NotificationException e) {
e.printStackTrace();
fail();
}
}
}
mockUserProviderContext.xml:
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd">
<bean id="simpleCertService" class="service.commons.defaults.CertificateService" />
<bean id="service" class="service.commons.defaults.EmailNotificationService" />
I'm getting the following exception whenever I try to run this unit test:
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:252)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:217)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:83)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
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:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:163)
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: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 'service': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:308)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
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.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.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)
... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:457)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:435)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:559)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:305)
... 41 more
The CertificateService class:
public class CertificateService implements CertificateUserService {
private static final Logger log = Logger.getLogger(SimpleCertificateService.class);
#Override
public User fetchUser(final X509Certificate certificate) {
log.info("Fetching user for " + certificate.getSubjectDN().getName());
return new SimpleUser(certificate.getSubjectDN().getName());
}
#Override
public User fetchUser(String name) {
log.info("Fetching user for " + name);
return new SimpleUser(name);
}
public class SimpleUser extends AbstractUser {
private static final long serialVersionUID = 1L;
public SimplUser(String username) {
super(username, "User", "thing", "User", "T1222", false);
this.emailAddress = "some#example.com";
this.phoneNumber = "(123)123-1234";
}
#Override
public void clearCache() {
super.clearCache();
}
}
}
Updated
I realized that I was not importing two context files, which I moved into src/test/resources, and are displayed here:
securityContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.1.xsd
">
<import resource="classpath:mongo-context.xml" />
<!-- This html element specifies that we'll use annotation driven method
security throughout our application. -->
<security:global-method-security
secured-annotations="enabled" pre-post-annotations="enabled" />
<!-- This element is what protects the various service and UI end points.
It specifies we'll use an x509 filter to pull out the subject principal common
name and use that to produce a given User object. -->
<security:http auto-config="true" use-expressions="true">
<security:csrf disabled="true" />
<security:intercept-url pattern="/**"
requires-channel="https" access="isAuthenticated()" />
<security:x509 subject-principal-regex="(.*)"
user-service-ref="userDetailsService" />
</security:http>
<!-- This bean is the authentication manager we'll use. -->
<beans:bean id="userAuthManager"
class="service.commons.security.AuthenticationManager" />
<!-- The bean is a UserDetails service that will provide the User object
for a given request. -->
<beans:bean id="userDetailsService"
class="service.commons.security.userDetailsService" />
<!-- This is the UserFactory object that will fetch a User from the SecurityContext. -->
<beans:bean class="service.commons.security.userFactory"
id="userFactory" />
<!-- This bean represents the session scoped User object. We use the
factory bean to fetch it from the SecurityContext and then scope it to a
session and make it available to the processing thread. -->
<beans:bean scope="session" factory-bean="userFactory"
factory-method="getUser" id="user" class="service.commons.security.User">
<aop:scoped-proxy />
</beans:bean>
<beans:bean id="emailServ" class = "ral.service.commons.defaults.EmailNotificationService" />
<!-- UserApplicationInfoService -->
<beans:bean id="userInfoService"
class="service.commons.user_info.UserApplicationInfoServiceImpl" />
</beans:beans>
service-commons.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:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
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/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- Scan for components in the service-commons library... -->
<context:component-scan base-package="service.commons"></context:component-scan>
</beans>
I then realized that I need to import another context file from another project into securityContext.xml to get access to certain beans that are missing.
The issue I'm having now is that when I run the tests, I get an IllegalStateException caused by a SAXParser exception with the following error message:
cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element 'import'. I tried changing my schemaLocation, adding the spring version, and tweaking the namespace, but I can't figure out why this SAXParserException keeps getting thrown. Any ideas?
Does CertificateService have a dependency that you aren't showing?
Also, the Spring junit runner normally creates a GenericApplicationContext rather than a WebApplicationContext. You need to add #WebAppConfiguration to create the latter.

Unit testing Services in Spring by Mocking DAO

I am using Mockito to mock my DAOS and test my Service Layer. This is an example of what I've got:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = { "classpath:/spring/programacion-service-test.xml" })
public class ProgramacionServiceUnitTest {
#Autowired
private ProgramacionService programacionService;
#InjectMocks
#Autowired
private IProgramacionDAO programacionDAO;
private Mapper mapper = new DozerMapper();
#Before
public void init() {
}
// Probamos comprobando el id.
#Test
public void saveProgramacionTest() {
ProgramacionDTO p = getEntityDTO();
Mockito.when(programacionDAO.persist(Matchers.any(Programacion.class))).thenAnswer(new Answer<Programacion>() {
#Override
public Programacion answer(InvocationOnMock invocation) throws Throwable {
Programacion programacion = (Programacion) invocation.getArguments()[0];
programacion.setIdProgramacion(1L);
return programacion;
}
});
try{
programacionService.altaProgramacion(p);
compareEntities(p, programacionService.getProgramacion(0L));
}catch(Exception e){
System.out.println("ERrOR:"+e.getMessage());
}
}
(...)
}
And this is my XML config:
<?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:jms="http://www.springframework.org/schema/jms"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mockito="http://www.mockito.org/spring/mockito" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="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/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd
http://www.mockito.org/spring/mockito http://www.mockito.org/spring/mockito.xsd">
<!-- Enable component scanning for defining beans with annotations. -->
<!-- END ANNOTATED CONFIGURATION -->
<bean id="programacionDAO" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.mypackages.dao.programacion.ProgramacionDAO" />
</bean>
<bean class="com.mypackages.service.ProgramacionService" />
<context:annotation-config />
<import resource="common-beans.xml" />
</beans>
The problem is -- I get an exception because I am not defining an EntityManagerFActory:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:91)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:74)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:116)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:82)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:212)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:199)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:251)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:253)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:216)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:82)
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:60)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:67)
at org.junit.runners.ParentRunner.run(ParentRunner.java:292)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:162)
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: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 'programacionDAO': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:356)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1204)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:538)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
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:725)
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.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:260)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:63)
at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:83)
... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:559)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:515)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:682)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:655)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:164)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:353)
... 41 more
Is this right? I am using a Mock and my IProgramacionDAO has no reference to an entityManager, so to my understanding it shouldnt' be trying to inject any EntityManagerFactories. If I explicitly declare my EM, it works, but I feel like I am loading a Persistence Context that I don't really need...

MockMvc: forwardedUrl is null

I am having problems to make this test work. Assertion always fails because it can't verify forwardedUrl which is always null. If I remove this assumption, it can't verify return model. I suppose it is due to missing forwarded Url. My test class looks like this:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:test-application-config.xml"})
#WebAppConfiguration
public class UserControllerTest {
private MockMvc mockMvc;
#Mock
private UserService userServiceMock;
#Inject
private WebApplicationContext wac;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
#Test
public void users_ShouldAddUserEntriesToModelAndRenderUserListView() throws Exception {
User firstUser = generateSampleUser("Pera", "Peric");
User secondUser = generateSampleUser("Maja", "Majic");
when(userServiceMock.getAllUsers()).thenReturn(Arrays.asList(firstUser, secondUser));
mockMvc.perform(get("/users"))
.andExpect(status().isOk())
.andExpect(view().name("users"))
.andExpect(forwardedUrl("/WEB-INF/velocity/users.vm"))
.andExpect(model().attribute("users", hasSize(2)))
.andExpect(model().attribute("users", hasItem(
allOf(
hasProperty("id", is(1L)),
hasProperty("firstName", is("Pera")),
hasProperty("LastName", is("Peric"))
)
)))
.andExpect(model().attribute("users", hasItem(
allOf(
hasProperty("id", is(2L)),
hasProperty("firstName", is("Maja")),
hasProperty("LastName", is("Majic"))
)
)));
verify(userServiceMock, times(1)).getAllUsers();
verifyNoMoreInteractions(userServiceMock);
}
private User generateSampleUser(String firstName, String lastName) {
User user = new User();
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail("test#email.com");
user.setBirthday(new Date());
user.setGender(Gender.MALE);
user.setPersonalNumber("1234567890123");
return user;
}
}
And test configuration file looks like this:
<?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"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="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">
<import resource="classpath:data-config-hsql.xml" />
<mvc:annotation-driven />
<context:component-scan base-package="com.code9" />
<bean id="velocityConfig"
class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
<property name="resourceLoaderPath" value="/WEB-INF/velocity/" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="layoutUrl" value="layout.vm" />
<property name="suffix" value=".vm" />
<property name="exposeSessionAttributes" value="true" />
</bean>
I must note that I'm just a beginner with spring mvc and that I'm not familiar with controller tests.
Edit: I forgot to add UserController implementation:
#Controller
public class UserController {
#Inject
private UserService userService;
#RequestMapping(value = "/users", method = RequestMethod.GET)
public ModelAndView getAllUsers() {
List<User> users = userService.getAllUsers();
return new ModelAndView("users", "users", users);
}
}
Edit: This is the full stack trace of exception that is causing this problem:
java.io.FileNotFoundException: class path resource [WEB-INF/velocity/] cannot be resolved to URL because it does not exist
at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:177)
at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:48)
at org.springframework.ui.velocity.VelocityEngineFactory.initVelocityResourceLoader(VelocityEngineFactory.java:304)
at org.springframework.ui.velocity.VelocityEngineFactory.createVelocityEngine(VelocityEngineFactory.java:234)
at org.springframework.web.servlet.view.velocity.VelocityConfigurer.afterPropertiesSet(VelocityConfigurer.java:119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1571)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1509)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:296)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:293)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:628)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:284)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
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:309)
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)
Does it work if you use your production config files instead of your test-application-config?
e.g.
#ContextConfiguration({"file:src/main/webapp/WEB-INF/applicationContext.xml",
"file:src/main/webapp/WEB-INF/dispatcher-servlet.xml"})
Maybe you need to add some ../ in the resourceLoaderPath.
e.g.
<property name="resourceLoaderPath" value="../main/webapp/WEB-INF/velocity/" />

Categories