This question already has answers here:
Why is my Spring #Autowired field null?
(21 answers)
Closed 7 years ago.
I wrote an integration test on a Spring Framework controller and the and test runs correct. Application runs correct too. I have some exceptions that i want to fix. I can not fix the nullpoiner exception which come from LoginController at line 34. I saw that loginDelegate but how ti fix this ?
Controller class
#Controller
public class LoginController {
#Autowired
private LoginDelegate loginDelegate;
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView displayLogin(HttpServletRequest request, HttpServletResponse response, LoginBean loginBean) {
ModelAndView model = new ModelAndView("login");
model.addObject("loginBean", loginBean);
return model;
}
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView executeLogin(ModelAndView model, HttpServletRequest request, HttpServletResponse response,
#ModelAttribute("loginBean") LoginBean loginBean) {
try {
boolean isValidUser = loginDelegate.isValidUser(loginBean.getUsername(), loginBean.getPassword());
if (isValidUser) {
System.out.println("User Login Successful");
request.setAttribute("loggedInUser", loginBean.getUsername());
model = new ModelAndView("welcome");
} else {
model = new ModelAndView("login");
request.setAttribute("message", "Invalid credentials!!");
}
} catch (Exception e) {
e.printStackTrace();
}
return model;
}
}
Test Controller Class
#EnableWebMvc
#WebAppConfiguration
#Configuration
#ContextConfiguration(locations = { "classpath:/WEB-INF/spring-dispatcher-servlet.xml" })
public class LoginControllerTest {
#Autowired
protected WebApplicationContext wac;
private MockMvc mockMvc;
#Before
public void setup() throws Exception {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
this.mockMvc = standaloneSetup(new LoginController()).setViewResolvers(viewResolver).build();
}
#Test
public void testDisplayLogin() throws Exception {
this.mockMvc.perform(get("/login")).andExpect(status().isOk()).andExpect(view().name("login")).andDo(print())
.andExpect(forwardedUrl("/WEB-INF/views/login.jsp"));
}
#Test
public void testExecuteLogin() throws Exception {
this.mockMvc.perform(post("/login").param("username", "nikola").param("password", "pass")).andDo(print())
.andExpect(status().isOk()).andExpect(view().name("login"));
}
}
spring dispacher servlet
<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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.nikola" />
<mvc:annotation-driven enable-matrix-variables="true" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<bean id="loginDelegate" class="com.nikola.integration.delegate.LoginDelegate">
<property name="userService" ref="userService"></property>
</bean>
<bean id="userService" class="com.nikola.integration.service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean name="userDao" class="com.nikola.integration.dao.impl.UserDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean name="loginController" class="com.nikola.integration.controller.LoginController">
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/store" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
</beans>
Exception
java.lang.NullPointerException
at com.nikola.integration.controller.LoginController.executeLogin(LoginController.java:34)
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.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:111)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:144)
at com.nikola.integration.controller.test.LoginControllerTest.testExecuteLogin(LoginControllerTest.java:51)
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.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.runners.ParentRunner.run(ParentRunner.java:363)
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)
In your test, you are instantiating a new LoginController :
this.mockMvc = standaloneSetup(new LoginController()).setViewResolvers(viewResolver).build();
This new instance is not managed by spring and the #Autowired field is not injected.
You should inject in your test the LoginController defined in your configuration, and initialize the mockMvc with this instance :
#Autowired
private LoginController controller;
...
this.mockMvc = standaloneSetup(c).setViewResolvers(viewResolver).build();
Related
MySQL, postgresql
I want to put the same data in the same name table.
Both databases have the same table.
error
WARN 2017-07-04 14:53:03 o.s.c.s.GenericApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'tempMasterServiceImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
INFO 2017-07-04 14:53:03 o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
INFO 2017-07-04 14:53:03 o.s.o.j.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
ERROR 2017-07-04 14:53:03 o.s.t.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#7af44dd0] to prepare test instance [jp.co.ui2.dev.server.c_one.tempServiceTest#26d8c9da]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) [junit-4.12.jar:4.12]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:363) [junit-4.12.jar:4.12]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) [spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) [.cp/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'courseMasterServiceImpl': Injection of persistence dependencies failed; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:357) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:776) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:861) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:541) ~[spring-context-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:128) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116) ~[spring-test-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManagerFactory] is defined: expected single matching bean but found 2: entityManagerFactoryBean,entityManagerFactoryBean2
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findDefaultEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:587) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.findEntityManagerFactory(PersistenceAnnotationBeanPostProcessor.java:546) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:712) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:685) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:169) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:354) ~[spring-orm-4.3.2.RELEASE.jar:4.3.2.RELEASE]
... 39 common frames omitted
test.properties
//mysql
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:8888/testdb
jdbc.username=test
jdbc.password=test
//postgresql
jdbc.driverClassName2=org.postgresql.Driver
jdbc.url2=jdbc:postgresql://localhost:5432/postgres
jdbc.username2=postgres
jdbc.password2=postgres
TestConfig.java
#Configuration
#Import({ testServerConfig.class })
public class TestConfig
{
#Bean
public PropertiesFactoryBean prop() {
PropertiesFactoryBean f = new PropertiesFactoryBean();
f.setLocations(new Resource[] {
new FileSystemResource("src/main/webapp/WEB-INF/config.properties"),
new ClassPathResource("test.properties", getClass())
});
return f;
}
}
tempServiceTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = TestConfig.class, loader =AnnotationConfigContextLoader.class)
public class ShopInfoServiceTest extends AbstractServiceTest
{
#Autowired
private tempMasterService tempService;
#Test
public void testCustomCode()
{
// insert
doInTransaction(new Runnable() {
#Override
public void run() {
tempMaster info = createTemp( );
tempService.insertTempMaster(info);
}
});
}
private tempMaster createTemp () {
tempMaster xxx = new tempMaster ();
xxx.setTempId(1);
xxx.setTempName("chaco1234");
xxx.setDescription("tttttt2232");
xxx.setUserId("admin");
return xxx;
}
}
testServerConfig.java
#Configuration
#ComponentScan(basePackages = { "com.co.test.dev" }, excludeFilters = {
#Filter(type = FilterType.ANNOTATION, value = Controller.class),
#Filter(type = FilterType.ANNOTATION, value = Configuration.class) })
#EnableTransactionManagement
#EnableScheduling
#EnableCaching
#ImportResource("classpath:job-context.xml")
public class testServerConfig
{
#Autowired
private ApplicationContext ctx;
#Autowired
private ResourceLoader resourceLoader;
#Value("#{prop['jdbc.driverClassName'] ?: ''}")
private String jdbcDriverClassName;
#Value("#{prop['jdbc.url'] ?: ''}")
private String jdbcUrl;
#Value("#{prop['jdbc.username'] ?: ''}")
private String jdbcUsername;
#Value("#{prop['jdbc.password'] ?: ''}")
private String jdbcPassword;
#Value("#{prop['jdbc.driverClassName2'] ?: ''}")
private String jdbcDriverClassName2;
#Value("#{prop['jdbc.url2'] ?: ''}")
private String jdbcUrl2;
#Value("#{prop['jdbc.username2'] ?: ''}")
private String jdbcUsername2;
#Value("#{prop['jdbc.password2'] ?: ''}")
private String jdbcPassword2;
#Value("#{prop['hibernate.dialect2'] ?: ''}")
private String hibernateDialect2;
#Value("#{prop['jdbc.initialSize'] ?: '0'}")
private int jdbcInitialSize;
#Value("#{prop['jdbc.maxActive'] ?: '50'}")
private int jdbcMaxActive;
#Value("#{prop['jdbc.maxIdle'] ?: '5'}")
private int jdbcMaxIdle;
#Value("#{prop['jdbc.maxWait'] ?: '5000'}")
private int jdbcMaxWait;
#Value("#{prop['jdbc.minIdle'] ?: '0'}")
private int jdbcMinIdle;
#Value("#{prop['jdbc.testWhileIdle'] ?: 'false'}")
private boolean jdbcTestWhileIdle;
#Value("#{prop['jdbc.testOnBorrow'] ?: 'false'}")
private boolean jdbcTestOnBorrow;
#Value("#{prop['jdbc.validationQuery'] ?: ''}")
private String jdbcValidationQuery;
#Value("#{prop['hibernate.hbm2ddl.auto'] ?: 'update'}")
private String hibernateDDLAuto;
#Value("#{prop['hibernate.dialect'] ?: ''}")
private String hibernateDialect;
#Value("#{prop['hibernate.search.indexBase'] ?: ''}")
private String searchIndexBase;
#Value("#{prop['hibernate.packages.to.scan'] ?: ''}")
private String packagesToScan;
protected String getRealPath(String path)
{
if ((ctx != null) && (ctx instanceof WebApplicationContext)
&& (((WebApplicationContext) ctx).getServletContext() != null)) return ((WebApplicationContext) ctx)
.getServletContext().getRealPath(path);
else return "src/main/webapp/" + path;
}
#Bean
public PropertiesFactoryBean prop()
{
String path = getRealPath("/WEB-INF/config.properties");
PropertiesFactoryBean f = new PropertiesFactoryBean();
f.setLocation(new FileSystemResource(path));
return f;
}
#Bean(name="dataSource")
public DataSource dataSource()
{
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(jdbcDriverClassName);
ds.setUrl(jdbcUrl);
ds.setUsername(jdbcUsername);
ds.setPassword(jdbcPassword);
ds.setInitialSize(jdbcInitialSize);
ds.setMaxActive(jdbcMaxActive);
ds.setMaxIdle(jdbcMaxIdle);
ds.setMaxWait(jdbcMaxWait);
ds.setMinIdle(jdbcMinIdle);
ds.setTestWhileIdle(jdbcTestWhileIdle);
ds.setValidationQuery(jdbcValidationQuery);
return ds;
}
#Bean(name="dataSource2")
public DataSource dataSource2()
{
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(jdbcDriverClassName2);
ds.setUrl(jdbcUrl2);
ds.setUsername(jdbcUsername2);
ds.setPassword(jdbcPassword2);
ds.setInitialSize(jdbcInitialSize);
ds.setMaxActive(jdbcMaxActive);
ds.setMaxIdle(jdbcMaxIdle);
ds.setMaxWait(jdbcMaxWait);
ds.setMinIdle(jdbcMinIdle);
ds.setTestWhileIdle(jdbcTestWhileIdle);
ds.setValidationQuery(jdbcValidationQuery);
return ds;
}
#Bean(name="entityManagerFactoryBean")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
{
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
if (packagesToScan != null) {
String[] pts = packagesToScan.split(",");
emf.setPackagesToScan(pts);
}
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties p = new Properties();
p.setProperty("hibernate.archive.autodetection", "class");
p.setProperty("hibernate.dialect", hibernateDialect);
p.setProperty("hibernate.show_sql", "false");
p.setProperty("hibernate.format_sql", "true");
p.setProperty("hibernate.hbm2ddl.auto", hibernateDDLAuto);
//naming-strategy
p.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
emf.setJpaProperties(p);
return emf;
}
#Bean(name="entityManagerFactoryBean2")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean2()
{
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource());
if (packagesToScan != null) {
String[] pts = packagesToScan.split(",");
emf.setPackagesToScan(pts);
}
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties p = new Properties();
p.setProperty("hibernate.archive.autodetection", "class");
p.setProperty("hibernate.dialect2", hibernateDialect2);
p.setProperty("hibernate.show_sql", "false");
p.setProperty("hibernate.format_sql", "true");
p.setProperty("hibernate.hbm2ddl.auto", hibernateDDLAuto);
//naming-strategy
p.setProperty("hibernate.ejb.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy");
emf.setJpaProperties(p);
return emf;
}
#Bean(name="transactionManager")
public PlatformTransactionManager transactionManager()
{
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactoryBean().getObject());
return tm;
}
#Bean(name="transactionManager2")
public PlatformTransactionManager transactionManager2()
{
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(entityManagerFactoryBean2().getObject());
return tm;
}
#Bean
public EhCacheCacheManager cacheManager()
{
EhCacheCacheManager cm = new EhCacheCacheManager();
cm.setCacheManager(ehcache().getObject());
return cm;
}
#Bean
public EhCacheManagerFactoryBean ehcache()
{
EhCacheManagerFactoryBean factory = new EhCacheManagerFactoryBean();
factory.setConfigLocation(resourceLoader.getResource("classpath:ehcache.xml"));
return factory;
}
#Bean(name = "configSftpSessionfactoryId")
public DefaultSftpSessionFactory sftpSessionFactory() {
DefaultSftpSessionFactory sftp = new DefaultSftpSessionFactory();
sftp.setHost(sftpHost);
sftp.setPort(sftpPort);
sftp.setUser(sftpUser);
sftp.setPassword(sftpPassword);
if (sftpPrivateKey != null && !"".equals(sftpPrivateKey)) {
sftp.setPrivateKey(resourceLoader.getResource(sftpPrivateKey));
sftp.setPrivateKeyPassphrase(sftpPrivateKeyPassphrase);
}
sftp.setAllowUnknownKeys(true);
return sftp;
}
}
tempMasterServiceImpl
#Service
#Transactional
#SwabAdminAuthCheck
public class tempMasterImpl implements tempMasterService{
private Logger logger = LoggerFactory.getLogger(getClass());
#PersistenceContext
private EntityManager em;
#Override
public void insertTempMaster(tempMaster obj) throws SwabException {
Query keyq = em.createQuery("select tempId from tempMaster where userId = :userId");
keyq.setParameter("userId", obj.getUserId());
Integer tmepId = null;
try{
tempId = (Integer)keyq.getSingleResult();
obj.setTempId( tempId );
} catch (NoResultException nre){
}
tempMaster searchData = em.find(tempMaster.class, obj);
if (searchData == null) {
logger.debug("insert");
em.persist(obj);
} else {
logger.debug("update");
em.merge(obj);
}
}
}
Will this source help?
datasourse-config.xml
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="dataSource2"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName2}" />
<property name="url" value="${jdbc.url2}" />
<property name="username" value="${jdbc.username2}" />
<property name="password" value="${jdbc.password2}" />
</bean>
<context:property-placeholder location="classpath:config.properties" />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<constructor-arg ref="entityManagerFactoryBean" />
</bean>
<bean id="transactionManager2" class="org.springframework.orm.jpa.JpaTransactionManager">
<constructor-arg ref="entityManagerFactoryBean2" />
</bean>
<bean id="entityManagerFactoryBean"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
</props>
</property>
</bean>
<bean id="entityManagerFactoryBean2"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource2" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect2}</prop>
</props>
</property>
</bean>
persistence.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyTenSevenDialect" />
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.EmbeddedDriver" />
</properties>
</persistence-unit>
</persistence>
spring-config.xml
<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"
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">
<bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
<property name="transactionManager" ref="transactionManager" />
</bean>
<bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
<property name="jobRepository" ref="jobRepository" />
</bean>
<!-- 非同期処理タスクExecutor -->
<bean id="asyncTaskExecutor" class="org.springframework.core.task.SimpleAsyncTaskExecutor" />
<!-- バリデーションプロセッサ -->
<bean id="validatingItemProcessor" class="org.springframework.batch.item.validator.ValidatingItemProcessor">
<property name="validator">
<bean class="org.springframework.batch.item.validator.SpringValidator">
<property name="validator">
<!-- Hibernate バリデータ -->
<bean name="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />
</property>
</bean>
</property>
</bean>
<!-- property config file -->
<bean id="propertyFilebean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="config.properties"/>
</bean>
<bean id="dummyTasklet" class="jp.co.ui2.sms.batch.tasklet.DummyTasklet">
<property name="batchStatus">
<value type="org.springframework.batch.core.BatchStatus">FAILED</value>
</property>
</bean>
</beans>
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trring to create an application where I am getting a problem. Here is the code
HomeController.java
#Controller
public class HomeController {
private EmployeeService employeeService;
#Autowired(required=true)
#Qualifier(value="employeeService")
public void setEmployeeService(EmployeeService employeeService)
{
this.employeeService = employeeService;
}
#RequestMapping("/index")
public ModelAndView indexWorld(#ModelAttribute("loginForm") Employee employee, ModelMap model) {
return new ModelAndView("index", "welcomeMessage","Hello Guest! welcome to our site");
}
#RequestMapping("/login")
public ModelAndView loginWorld(#ModelAttribute("loginForm") Employee employee, ModelMap model){
String result="", returnPage="";
if(this.employeeService.validateLogin(employee.getUsername(), employee.getPassword())){
result = "Welcome " + employee.getUsername();
returnPage = "home";
}
else{
result = "<BR>Login Failure";
returnPage = "index";
}
model.addAttribute("result", result);
return new ModelAndView(returnPage, model);
}
}
EmployeeServiceImpl.java
#Service
public class EmployeeServiceImpl implements EmployeeService {
/* (non-Javadoc)
* #see com.smart.service.EmployeeService#validateLogin(java.lang.String, java.lang.String)
*/
EmployeeDAO employeeDAO;
public void setEmployeeDAO(EmployeeDAO employeeDAO)
{
this.employeeDAO = employeeDAO;
}
#Override
public boolean validateLogin(String username, String password) {
// TODO Auto-generated method stub
return this.employeeDAO.validateLogin(username, password);
}
}
EmployeeDAOImpl.java
#Transactional(value="myTransactionManager")
public class EmployeeDaoImpl implements EmployeeDAO {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
#Override
public boolean validateLogin(String username, String password) {
return (long)this.sessionFactory.getCurrentSession().createQuery("SELECT COUNT(*) FROM EmployeeInfo WHERE username = :username AND password = :password")
.setString("username", username)
.setString("password", password).uniqueResult() > 0;
}
}
welcome-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"
xmlns:mvc="http://www.springframework.org/schema/mvc">
<context:annotation-config />
<context:component-scan base-package="com.smart" />
<mvc:annotation-driven />
<tx:annotation-driven transaction-manager="myTransactionManager" />
<bean id="employeeService" class="com.smart.service.EmployeeServiceImpl"></bean>
<bean id="employeeDAO" class="com.smart.dao.EmployeeDaoImpl"></bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/view/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="oracle.jdbc.OracleDriver"
p:url="jdbc:oracle:thin:#localhost:1521:IMS"
p:username="username"
p:password="password" />
<mvc:resources mapping="/resources/**" location="/resources/theme1/" />
</beans>
Error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.NullPointerException
com.smart.service.EmployeeServiceImpl.validateLogin(EmployeeServiceImpl.java:32)
com.smart.controller.HomeController.loginWorld(HomeController.java:38)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
I am getting in EmployeeServiceImpl.java on this line
return this.employeeDAO.validateLogin(username, password);
It seems I am getting null from validateLogin function although I am return value from validateLogin function. Why I am getting null?
EDIT
Now error
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myTransactionManager' is defined: No matching PlatformTransactionManager bean found for qualifier 'myTransactionManager' - neither qualifier match nor bean name match!
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'myTransactionManager' is defined: No matching PlatformTransactionManager bean found for qualifier 'myTransactionManager' - neither qualifier match nor bean name match!
org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactoryAnnotationUtils.java:100)
org.springframework.beans.factory.annotation.BeanFactoryAnnotationUtils.qualifiedBeanOfType(BeanFactoryAnnotationUtils.java:56)
org.springframework.transaction.interceptor.TransactionAspectSupport.determineQualifiedTransactionManager(TransactionAspectSupport.java:377)
org.springframework.transaction.interceptor.TransactionAspectSupport.determineTransactionManager(TransactionAspectSupport.java:358)
org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:271)
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
com.sun.proxy.$Proxy37.validateLogin(Unknown Source)
com.smart.service.EmployeeServiceImpl.validateLogin(EmployeeServiceImpl.java:33)
com.smart.controller.HomeController.loginWorld(HomeController.java:38)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
It seems EmployeeDAO is not being injected in EmployeeServiceImpl, wire EmployeeDAO using #Autowire or #Inject, Second EmployeeDAOImpl has not been declared a component (not sure if you have declared already in xml) so declare it with #Repository and also #Autowire SessionFactory. Hope this will do..
From the stacktrace it appears your code never calls validateLogin on the dao. The dao is null because there's nothing telling Spring to wire your DAO into your service. Add an #Autowired annotation to the setter in the service for the dao, similar to what you have in the controller wiring the service into it.
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/" />
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
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);
}