Hibernate Sessions - java

I have a problem during studying Hibernate. I wrote UnitTest and there i try to add object into DB. All selects are working properly, but insert not working so.
public class HibernateTutorial extends BaseTest {
#Autowired
SessionFactory sessionFactory;
#Test
#Transactional
public void hibernateTutorial() {
#SuppressWarnings("unchecked")
List<User> users = sessionFactory.getCurrentSession().createQuery("from User").list();
sessionFactory.getCurrentSession().saveOrUpdate(new User("HiberTest", "HiberPass", "Hiber#Mail.ru", "HiberSurname",
"HiberLastname", "HiberAddress", "123432"));
}
I also try something like this
public class HibernateTutorial extends BaseTest {
#Autowired
SessionFactory sessionFactory;
#Test
#Transactional
public void hibernateTutorial() {
#SuppressWarnings("unchecked")
List<User> users = sessionFactory.getCurrentSession().createQuery("from User").list();
sessionFactory.getCurrentSession().saveOrUpdate(
new User("HiberTest", "HiberPass", "Hiber#Mail.ru", "HiberSurname", "HiberLastname", "HiberAddress", "123432"));
sessionFactory.getCurrentSession().getTransaction().commit();
}
}
It throw me Exception that Transaction not succesfully started, but it add user
Here is an Exception
org.springframework.transaction.TransactionSystemException: Could not
roll back Hibernate transaction; nested exception is
org.hibernate.TransactionException: Transaction not successfully
started at
org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:679)
at
org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:845)
at
org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:822)
at
org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:512)
at
org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:290)
at
org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:183)
at
org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:406)
at
org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:90)
at
org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193) at
org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52) at
org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191) at
org.junit.runners.ParentRunner.access$000(ParentRunner.java:42) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184) at
org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at
org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236) at
org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
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.hibernate.TransactionException: Transaction not
successfully started at
org.hibernate.transaction.JDBCTransaction.rollback(JDBCTransaction.java:183)
at
org.springframework.orm.hibernate3.HibernateTransactionManager.doRollback(HibernateTransactionManager.java:676)
... 25 more

I can see 2 problems in your code.
1 -Your transactions have not been started.
Answer: You have to use the getSession().beginTransaction() method before you do anything on Database.
2 - There's no rollback method in case your transactions fails
Answer: Use a try-catch block, see example below.
Example of my code:
public void salvarDB(Object object)
{
Session session = HibernateUtil.getSession();
HibernateUtil.beginTransaction();
try
{
session.save(object);
HibernateUtil.commit();
avisos.salvoComSucesso(object);
}
catch(ConstraintViolationException e)
{
avisos.registroJaInserido(object);
HibernateUtil.rollback();
}
catch (Exception ex) {
avisos.falhaAoSalvar(object);
HibernateUtil.rollback();
}
finally {
HibernateUtil.closeSession();
}
}

Related

Why the EntityManager is closed?

I'm developing a small stock control application using Java-SE8, JPA and Hibernate and this is my first contact with ORMs and the Persistence API. All was fine, but my tests failed when I created a method to retrieve things on the database(MySQL) and I get an:
"IllegalStateException: Entity Manager is closed."
I really don't know what is happening and spent almost two days trying to fix this. Can anyone help me, please?
Here are the pieces of code that trigger the error.
DAO.java
private EntityManager getEntityManager() {
EntityManagerFactory factory = null;
EntityManager entityManager = null;
try {
factory = Persistence.createEntityManagerFactory("stockcontrol");
entityManager = factory.createEntityManager();
} finally {
factory.close();
}
return entityManager;
}
public <T> List<T> findAllByClass(Class clazz) {
EntityManager manager = null;
try{
manager = getEntityManager();
String hql = "FROM " + clazz.getName();
Query hqlQuery = manager.createQuery(hql);
return hqlQuery.getResultList();
} finally {
manager.close();
}
}
Moneytory.java
DAO dao = new DAO();
public static void registerProduct(String name, int amount, double unitPrice,
String strCategory) throws RegisterException {
List<Product> products = dao.findAllByClass(Product.class);
List<Category> categories = dao.findAllByClass(Category.class);
if(products.contains(getProductByName(name)))
throw new RegisterException("The product already exists");
Product newProduct = null;
Category newCategory = null;
try{
newCategory = new Category(strCategory);
newProduct = new Product(name, amount, unitPrice, newCategory);
} catch(IllegalArgumentException e){
throw new RegisterException(e.getMessage());
}
if(!categories.contains(newCategory))
dao.persist(newCategory);
dao.persist(newProduct);
dao.flush();
}
And the StackTrace I've got:
java.lang.IllegalStateException: EntityManager is closed
at org.hibernate.jpa.internal.EntityManagerImpl.checkOpen(EntityManagerImpl.java:105)
at org.hibernate.jpa.internal.EntityManagerImpl.checkOpen(EntityManagerImpl.java:96)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:326)
at br.edu.noorg.moneytory.dao.DAO.findAllByClass(DAO.java:154)
at br.edu.noorg.moneytory.core.MoneyTory.registerProduct(MoneyTory.java:111)
at br.edu.noorg.moneytory.test.MoneyToryTest.mustRegisterProduct(MoneyToryTest.java:92)
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:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
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.runners.ParentRunner.run(ParentRunner.java:309)
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)
So you created an EntityManagerFactory (EMF), then an EntityManager (from the EMF), and then closed the EntityManagerFactory… which will close all of the EntityManager that it owns. Don't close the EMF!!

#After method being run first by JUnit

I am running into a strange issue with my JUnit test case: the #After method is invoked first by JUnit.
Here is the abstract class I use for my test:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = { TestServicePlusRepositoryIntegrationConfiguration.class })
#ActiveProfiles(Profiles.TEST)
#Transactional
public abstract class AbstractServicePlusRepositoryIntegrationTest {
}
Here is the problematic test case:
public class AdvertisementServiceSecurityTest extends AbstractServicePlusRepositoryIntegrationTest {
...
#Before
public void setUp() {
advertisement = advertisementFactory.createAdvertisement(OWNER_OF_ADVERTISEMENT_EMAIL);
impersonator = memberFactory.createMember(IMPERSONATOR_EMAIL, Role.ROLE_BASIC_CHILDCAREWORKER);
when(geolocationServiceMock.retrieveAddressFromReference("valid-reference")).thenReturn(new Address());
}
#After
public void tearDown() {//Executed first!
advertisementFactory.deleteAdvertisement(advertisement);
memberFactory.deleteMember(impersonator);
}
...
#Test(expected = AccessDeniedException.class)
#WithUserDetails(IMPERSONATOR_EMAIL)
public void deleteAdvertisementByIdWithInvalidMember() {
advertisementService.deleteAdvertisement(advertisement.getId());
}
What could cause the #After method to run first? FYI, I don't use JUnit 3.
Here is the full source code for the test case: https://gist.github.com/balteo/e8c2ea96db22d3f9c88e
It appears an exception was raised in the #Before method causing it not to complete:
2014-11-08 13:39:12.169 WARN 4513 --- [ main] o.s.test.context.TestContextManager : Caught exception while allowing TestExecutionListener [org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener#44c03695] to process 'before' execution of test method [public void com.bignibou.it.service.advertisement.AdvertisementServiceSecurityTest.deleteAdvertisementByIdWithInvalidMember()] for test instance [com.bignibou.it.service.advertisement.AdvertisementServiceSecurityTest#49438269]
java.lang.IllegalStateException: Unable to create SecurityContext using #org.springframework.security.test.context.support.WithUserDetails(value=joe.hacker#gmail.com)
at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createSecurityContext(WithSecurityContextTestExecutionListener.java:84)
at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.beforeTestMethod(WithSecurityContextTestExecutionListener.java:60)
at org.springframework.test.context.TestContextManager.beforeTestMethod(TestContextManager.java:249)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:72)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:82)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:73)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
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.security.core.userdetails.UsernameNotFoundException: Username: joe.hacker#gmail.com not found!
at com.bignibou.service.security.MemberUserDetailsService.loadUserByUsername(MemberUserDetailsService.java:22)
at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:48)
at org.springframework.security.test.context.support.WithUserDetailsSecurityContextFactory.createSecurityContext(WithUserDetailsSecurityContextFactory.java:36)
at org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener.createSecurityContext(WithSecurityContextTestExecutionListener.java:82)
... 24 common frames omitted
tearDown
Using Spring's #BeforeTransaction see javadocs here allowed the test to run and pass:
#BeforeTransaction
public void setUp() {
System.out.println("setUp");
advertisement = advertisementFactory.createAdvertisement(OWNER_OF_ADVERTISEMENT_EMAIL);
impersonator = memberFactory.createMember(IMPERSONATOR_EMAIL, Role.ROLE_BASIC_CHILDCAREWORKER);
when(geolocationServiceMock.retrieveAddressFromReference("valid-reference")).thenReturn(new Address());
}
#AfterTransaction
public void tearDown() {
System.out.println("tearDown");
advertisementFactory.deleteAdvertisement(advertisement);
memberFactory.deleteMember(impersonator);
}

How to rewrite mockControl test to spring 4

In spring 3.6 I am testing client side according to this example: http://javacrumbs.net/spring-ws-test/
Problem is this doesn work with spring 4. It throw exception:
java.lang.IncompatibleClassChangeError: Found interface org.springframework.test.context.TestContext, but class was expected
at net.javacrumbs.springws.test.simple.annotation.WsMockControlTestExecutionListener.prepareTestInstance(WsMockControlTestExecutionListener.java:47)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
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:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
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)
how should I rewrite this test to spring 4 ?
First I try to debug this error with some more information so I create class:
import net.javacrumbs.springws.test.simple.annotation.WsMockControlTestExecutionListener;
import net.javacrumbs.springws.test.util.MockMessageSenderInjector;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.test.context.TestContext;
public class WsMockControlTestExecutionSpring4Listener extends WsMockControlTestExecutionListener {
private static final String MESSAGE_SENDER_BEAN_NAME = "net.javacrumbs.springws.test.simple.annotation.WsMockControlMockWebServiceMessageSender";
private static final String MOCK_CONTROL_BEAN_NAME = "net.javacrumbs.springws.test.simple.annotation.WsMockControl";
#Override
public void prepareTestInstance(TestContext testContext) throws Exception {
ConfigurableListableBeanFactory beanFactory = ((AbstractApplicationContext) testContext.getApplicationContext())
.getBeanFactory();
if (!beanFactory.containsBean(MOCK_CONTROL_BEAN_NAME)) {
beanFactory.registerSingleton(MOCK_CONTROL_BEAN_NAME, createWsMockControlFactoryBean());
beanFactory.registerSingleton(MESSAGE_SENDER_BEAN_NAME, createMessageSender());
new MockMessageSenderInjector().postProcessBeanFactory(beanFactory);
}
}
}
and in test I used this listener:
#TestExecutionListeners({ WsMockControlTestExecutionSpring4Listener.class,
DependencyInjectionTestExecutionListener.class })
and now the weird part. Tests are again working but I really dont understand why. I did nothing. Just override method prepareTestInstance with the exactly same code as in WsMockControlTestExecutionListener. Can someone explain me this "solution"

Spring ROO: JUnit test fails

I am having trouble executing my Spring IntegrationTests, when i run the code below it is failing at the persist method:
#RooIntegrationTest(entity = Person.class)
public class PersonIntegrationTest {
#Test
public void test() {
}
#Test
public void testCountPeople(){
Person personToPersist = PersonTestUtil.createTestPerson();
personToPersist.persist();
Long count = Person.countPeople();
assertNotNull(personToPersist);
assertTrue(personToPersist.countPeople() == 1);
}
}
The Stack trace is below
java.lang.IllegalStateException: Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethod$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$entityManager(Person_Roo_Entity.aj:95)
at org.bixin.dugsi.domain.Person.entityManager(Person.java:1)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethodDispatch1$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$entityManager(Person_Roo_Entity.aj)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethod$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$persist(Person_Roo_Entity.aj:58)
at org.bixin.dugsi.domain.Person.persist(Person.java:1)
at org.bixin.dugsi.domain.Person_Roo_Entity.ajc$interMethodDispatch1$org_bixin_dugsi_domain_Person_Roo_Entity$org_bixin_dugsi_domain_Person$persist(Person_Roo_Entity.aj)
at org.bixin.dugsi.domain.PersonIntegrationTest.testCountPeople(PersonIntegrationTest.java:25)
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:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
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)
Anyone run into this problem?
It seems that you have not injected the EntityManager and the related application context to your test.
Please try adding the following line above the class declaration.
#ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml","/META-INF/spring/applicationContext-security.xml" })
and try making your test class to inhert from AbstractJUnit4SpringContextTests. Do keep in mind that you might have to implement authentication for some operations to be executed.
Your test class could look like below.
package com.myapp.test;
#ContextConfiguration(locations = { "/META-INF/spring/applicationContext.xml","/META-INF/spring/applicationContext-security.xml" })
public class TestMyService extends AbstractJUnit4SpringContextTests {
#Autowired
MyService service = new MyService();
private void setUp() {
//Do the setting up of your classes for the test
}
#Test
public void testOperation() throws IOException {
//My Test Code here
}
}
Note that you should generally have a different context for your testing purposes.
Cheers.
If you're using Springsource Tool Suite (or another Eclipse) try to clean the project. I think Eclipse someimes doesn't use the AJDT Compiler, specially at startup.
I don't remember this message from the Roo console, that uses maven under the hood.
Try "perform eclipse" from the Roo shell or even maven directly from the console (mvn clean install or something like that)
It seems that you forgot to inject the EntityManager and the application context.
Try something like this, it worked for me with Spring Roo:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import com.jitter.finance.analyzer.domain.Address;
#ContextConfiguration(locations = { "classpath*:/META-INF/spring/applicationContext*.xml"})
public class EmTest extends AbstractJUnit4SpringContextTests {
#Test
public void checkEm(){
Address a = new Address();
a.setName("Primo");
a.persist();
Address b = new Address();
b.setName("Secondo");
b.persist();
for(Address ad : Address.findAllAddresses()){
System.out.println(ad.getName());
assertEquals(ad.getName().charAt(ad.getName().length()-1), 'o');
}
}
}

On accessing database through test I get play.exceptions.JPAException: The JPA context is not initialized

I am trying to access the database through a class using PlayFremwork and writing a test
import static org.junit.Assert.*;
import javax.persistence.EntityManager;
import models.com.vlist.entity.classes.Playlist;
import org.junit.Test;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import play.jobs.OnApplicationStart;
import play.mvc.Scope.Session;
public class PlaylistTest {
#Test
#Transactional
public void insertIntoPlaylist() {
Playlist playlist = new Playlist();
playlist.setId(1);
playlist.setName("test");
EntityManager em = JPA.em();
em.persist(playlist);
}
}
The error stacktrace is:
play.exceptions.JPAException: The JPA context is not initialized. JPA Entity Manager automatically start when one or more classes annotated with the #javax.persistence.Entity annotation are found in the application.
at play.db.jpa.JPA.get(JPA.java:22)
at play.db.jpa.JPA.em(JPA.java:51)
at PlaylistTest.insertIntoPlaylist(PlaylistTest.java:23)
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:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
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)
How can I resolve this issue while writing test?
Thank you
FIXED!! By extending FunctionalTest
public class PlaylistTest extends FunctionalTest {
#Test
#Transactional
public void insertIntoPlaylist() {
Playlist playlist = new Playlist();
playlist.setName("new_playlist_again");
EntityManager em = JPA.em();
em.persist(playlist);
}
}
public class PlaylistTest extends FunctionalTest {
#Test
#Transactional
public void insertIntoPlaylist() {
Playlist playlist = new Playlist();
playlist.setName("new_playlist_again");
EntityManager em = JPA.em();
em.persist(playlist);
}
}

Categories

Resources