Class DAOTestRule

  • All Implemented Interfaces:
    org.junit.rules.TestRule

    public class DAOTestRule
    extends org.junit.rules.ExternalResource
    A JUnit rule for testing DAOs and Hibernate entities. It allows to quickly test the database access code without starting the Dropwizard infrastructure.

    Example:

    
     @Rule
        public DAOTestRule daoTestRule = DAOTestRule.newBuilder()
              .addEntityClass(Person.class)
              .build();
    
        private PersonDAO personDAO;
    
       @Before
        public void setUp() throws Exception {
            personDAO = new PersonDAO(daoTestRule.getSessionFactory());
        }
    
       @Test
        public void createPerson() {
            Person wizard = daoTestRule.inTransaction(() -> personDAO.create(new Person("Merlin", "The chief wizard")));
            assertThat(wizard.getId()).isGreaterThan(0);
            assertThat(wizard.getFullName()).isEqualTo("Merlin");
            assertThat(wizard.getJobTitle()).isEqualTo("The chief wizard");
        }
     

    • Method Detail

      • newBuilder

        public static DAOTestRule.Builder newBuilder()
        Creates a new builder for DAOTestRule, which allows to customize a SessionFactory by different parameters. By default uses the H2 database in the memory mode.
        Returns:
        a new DAOTestRule.Builder
      • before

        protected void before()
                       throws Throwable
        Overrides:
        before in class org.junit.rules.ExternalResource
        Throws:
        Throwable
      • after

        protected void after()
        Overrides:
        after in class org.junit.rules.ExternalResource
      • getSessionFactory

        public org.hibernate.SessionFactory getSessionFactory()
        Returns the current active session factory for injecting to DAOs.
        Returns:
        SessionFactory with an open session.
      • inTransaction

        public <T> T inTransaction​(Callable<T> call)
        Performs a call in a transaction
        Type Parameters:
        T - the type of the returned result
        Parameters:
        call - the call
        Returns:
        the result of the call
      • inTransaction

        public void inTransaction​(Runnable action)
        Performs an action in a transaction
        Parameters:
        action - the action