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

  • SEARCH
  • Home
  • 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 7071905
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T05:44:38+00:00 2026-05-28T05:44:38+00:00

I’m trying to test my DAO layer (which is built on JPA) in separation.

  • 0

I’m trying to test my DAO layer (which is built on JPA) in separation. In the unit test, I’m using DbUnit to populate the database and Spring Test to get an instance of ApplicationContext.

When I tried to use the SpringJunit4ClassRuner, the ApplicationContext got injected, but the DbUnit’s getDataSet() method never got called.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
    ...

Then I tried to remove the @RunWith annotation, that removed the problems with getDataSet() method. But now I no longer get ApplicationContext instance injected. I tried to use the @TestExecutionListeners annotation, which is supposed to configure the DependencyInjectionTestExecutionListener by default, but the AppContext still doesn’t get injected.

@TestExecutionListeners
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {
    ...

Does anyone have any ideas? Is it generally a bad idea to combine these two frameworks?


EDIT: here is the rest of the source for the test class:

@TestExecutionListeners
@ContextConfiguration(locations = "/testdao.xml")
public class SimpleJPATest extends DBTestCase implements ApplicationContextAware {

    static final String TEST_DB_PROPS_FILE = "testDb.properties";
    static final String DATASET_FILE = "testDataSet.xml";
    static Logger logger = Logger.getLogger( SimpleJPATest.class );
    private ApplicationContext ctx;

    public SimpleJPATest() throws Exception {
        super();
        setDBUnitSystemProperties(loadDBProperties());
    }

    @Test
    public void testSimple() {
        EntityManagerFactory emf = ctx.getBean("entityManagerFactory", EntityManagerFactory.class);
        EntityManager em = emf.createEntityManager();
        GenericDAO<Club> clubDAO = new JpaGenericDAO<Club>(ClubEntity.class, "ClubEntity", em);
        em.getTransaction().begin();
        Collection<Club> allClubs = clubDAO.findAll();
        em.getTransaction().commit();
        assertEquals(1, allClubs.size());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         this.ctx = applicationContext;
    }

    private void setDBUnitSystemProperties(Properties props) {
        System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_DRIVER_CLASS,
                props.getProperty("db.driver"));
        System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_CONNECTION_URL,
                props.getProperty("db.url"));
        System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_USERNAME,
                props.getProperty("db.username"));
        System.setProperty(PropertiesBasedJdbcDatabaseTester.DBUNIT_PASSWORD,
                props.getProperty("db.password"));

    }

    private Properties loadDBProperties() throws Exception {
        URL propsFile = ClassLoader.getSystemResource(TEST_DB_PROPS_FILE);
        assert (propsFile != null);
        Properties props = new Properties();
        props.load(propsFile.openStream());
        return props;
    }

    @Override
    protected void setUpDatabaseConfig(DatabaseConfig config) {
        config.setProperty( DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
            new HsqldbDataTypeFactory() );
    }

    @Override
    protected DatabaseOperation getSetUpOperation() throws Exception {
        return DatabaseOperation.CLEAN_INSERT;
    }

    @Override
    protected DatabaseOperation getTearDownOperation() throws Exception {
        return DatabaseOperation.DELETE_ALL;
    }

    @Override
    protected IDataSet getDataSet() throws Exception {
        logger.debug("in getDataSet");
        URL dataSet = ClassLoader.getSystemResource(DATASET_FILE);
        assert (dataSet != null);
        FlatXmlDataSet result = new FlatXmlDataSetBuilder().build(dataSet);
        return result;
    }
}
  • 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-05-28T05:44:39+00:00Added an answer on May 28, 2026 at 5:44 am

    I’ve used these two frameworks together without any issues. I’ve had to do some things a little different from the standard though to get it to work:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = { "classpath:applicationContext.xml" })
    @TestExecutionListeners({ DependencyInjectionTestExecutionListener.class,
            DirtiesContextTestExecutionListener.class })
    public class MyDaoTest extends DBTestCase {
    
    @Autowired
    private MyDao myDao;
    
    /**
     * This is the underlying BasicDataSource used by Dao. If The Dao is using a
     * support class from Spring (i.e. HibernateDaoSupport) this is the
     * BasicDataSource that is used by Spring.
     */
    @Autowired
    private BasicDataSource dataSource;
    
    /**
     * DBUnit specific object to provide configuration to to properly state the
     * underlying database
     */
    private IDatabaseTester databaseTester;
    
    /**
     * Prepare the test instance by handling the Spring annotations and updating
     * the database to the stale state.
     * 
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        databaseTester = new DataSourceDatabaseTester(dataSource);
        databaseTester.setDataSet(this.getDataSet());
        databaseTester.setSetUpOperation(this.getSetUpOperation());
        databaseTester.onSetup();
    }
    
    /**
     * Perform any required database clean up after the test runs to ensure the
     * stale state has not been dirtied for the next test.
     * 
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception {
        databaseTester.setTearDownOperation(this.getTearDownOperation());
        databaseTester.onTearDown();
    }
    
    /**
     * Retrieve the DataSet to be used from Xml file. This Xml file should be
     * located on the classpath.
     */
    @Override
    protected IDataSet getDataSet() throws Exception {
        final FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
        builder.setColumnSensing(true);
        return builder.build(this.getClass().getClassLoader()
                .getResourceAsStream("data.xml"));
    }
    
    /**
     * On setUp() refresh the database updating the data to the data in the
     * stale state. Cannot currently use CLEAN_INSERT due to foreign key
     * constraints.
     */
    @Override
    protected DatabaseOperation getSetUpOperation() {
        return DatabaseOperation.CLEAN_INSERT;
    }
    
    /**
     * On tearDown() truncate the table bringing it back to the state it was in
     * before the tests started.
     */
    @Override
    protected DatabaseOperation getTearDownOperation() {
        return DatabaseOperation.TRUNCATE_TABLE;
    }
    
    /**
     * Overridden to disable the closing of the connection for every test.
     */
    @Override
    protected void closeConnection(IDatabaseConnection conn) {
        // Empty body on purpose.
    }
    // Continue TestClass here with test methods.
    

    I’ve had to do things a little more manual than I would like, but the same scenario applies if you try to use the JUnit Parameterized runner with Spring (in that case you have to start the TextContext manually). The most important thing to note is that I override the closeConnection() method and leave it blank. This overrides the default action of closing the dataSource connection after each test which can add unnecessary time as the connection will have to be reopened after every test.

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

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I used javascript for loading a picture on my website depending on which small
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I am reading a book about Javascript and jQuery and using one of the
I am trying to render a haml file in a javascript response like so:
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and

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.