Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8181367
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T00:29:54+00:00 2026-06-07T00:29:54+00:00

I have the following test case: @ContextConfiguration(/spring/test-context.xml) @TransactionConfiguration(transactionManager=txManager) @Transactional() public class MyEntityDaoTestCase extends AbstractJUnit4SpringContextTests

  • 0

I have the following test case:

@ContextConfiguration("/spring/test-context.xml")
@TransactionConfiguration(transactionManager="txManager")
@Transactional()
public class MyEntityDaoTestCase extends AbstractJUnit4SpringContextTests { 

    @Autowired
    private MyEntityDao dao;

    @Test
    public void testSave_success() {
        MyEntity e = new MyEntity();
        dao.save(e);
        MyEntity result = dao.findById(e.getId());
        assertNotNull(result);      
    }
}

My DAO definition has as follows:

public abstract class MyEntityDAO {

    @PersistenceContext
    private EntityManager mEntityManager;

    public void save(MyEntity entity) {
        mEntityManager.persist(entity);
    }

    public MyEntity findById(Long id) {
        return mEntityManager.find(mEntityClass, id);
    }
}

My Spring config is the following:

<beans xmlns="http://www.springframework.org/schema/beans" 
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

    <!-- 
        Bean post-processor for JPA annotations 
    -->
    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

    <!--
        JPA entity manager factory 
     -->
    <bean id="jpaEntityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="unit-test-pu"/>
    </bean>

    <!--
        Transaction manager 
     -->
    <bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="jpaEntityManagerFactory"/>
    </bean>

    <!-- 
        Enable the configuration of transactional behavior based on annotations 
    -->
    <tx:annotation-driven transaction-manager="txManager"/>

    <!--
        DAO instance beans 
     -->
    <bean id="mockEntityDao" class="mypackage.MyEntityDao"></bean>

</beans>

I get no errors while executing my test but it won’t pass. It looks like the findById() method will not find the entity in the database. Can anyone advise on how to correctly test this case?

EDIT:

My JPA provider is hibernate. I am using an in-memory HSQLDB for my unit tests and have the following configuration:

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
             version="2.0">
   <persistence-unit name="unit-test-pu" transaction-type="RESOURCE_LOCAL">   
      <properties>
         <property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbcDriver"/>
         <property name="javax.persistence.jdbc.user" value="sa"/>
         <property name="javax.persistence.jdbc.password" value=""/>
         <property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:."/>
         <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
         <property name="hibernate.archive.autodetection" value="class"/>
         <property name="hibernate.show_sql" value="true"/>
         <property name="hibernate.format_sql" value="true"/>
         <property name="hibernate.hbm2ddl.auto" value="create"/>
      </properties>      
   </persistence-unit>
</persistence>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T00:29:56+00:00Added an answer on June 7, 2026 at 12:29 am

    If you follow TDD strictly you should not use an in memory database but instead have everything mocked. The problem is that the persist method returns void. So you can not test the correct response (an entity with an id generated by a database) One way to work around this is to us the Mockito doAnswer method, here an example:

    @RunWith(MockitoJUnitRunner.class)
    public class CookieRepositoryTest {
    
    @Mock
     EntityManager em;
    
    @Mock
     TimeService timeService;
    
    @InjectMocks
     CookieRepository underTest = new CookieRepository();
    
    @Test
     public void testCreateEntity() throws Exception {
     Cookie newCookie = new Cookie();
    
    when(timeService.getTime()).thenReturn(new DateTime(DateTimeZone.UTC));
    
    doAnswer(new Answer<Brand>() {
     @Override
     public Brand answer(InvocationOnMock invocationOnMock) throws Throwable {
     Object[] args = invocationOnMock.getArguments();
     Cookie cookie = (Cookie) args[0];
     cookie.setId(1);
     return null;
     }
    
    }).when(em).persist(any(Brand.class));
    
    Cookie persistedCookie = underTest.createEntity(newCookie);
     assertNotNull(persistedCookie.getId());
     }
    
    }
    

    A complete explanation can be found on my blog post.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have following test class @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {/services-test-config.xml}) public class MySericeTest { @Autowired
I have the following test case: include_once('../Logger.php'); class LoggerTest extends PHPUnit_Framework_TestCase { public function
When I have the following auto test case : class MyException: virtual public boost::exception,
I have following test.pyx cdef public class Foo[object Foo, type FooType]: cdef public char*
I have the following django test case that is giving me errors: class MyTesting(unittest.TestCase):
I have the following code with the corresponding test case: class XXX attr_accessor :source
I have the following test case [TestMethod()] [DeploymentItem(Courses.sdf)] public void RemoveCourseConfirmedTest() { CoursesController_Accessor target
I have the following test case in my iOS application : -(void) testTwoDefaultUsersExist {
I have the following code in test.sh: while getopts f:i: opt; do case $opt
I have the following code require 'test_helper' class ApplicationControllerTest < ActionController::TestCase test should display

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.