Class EmbeddedDatabaseRule

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

    public class EmbeddedDatabaseRule
    extends org.junit.rules.ExternalResource
    A JUnit 4 Rule that can be used to start/stop embedded database.
    Note that:
    • When used as a ClassRule, the embedded database will be started before all tests, and stopped after all tests.
    • When used as a Rule, the embedded database will be started before each test, and stopped after each test.
    Here is an example using the ClassRule annotation:
    
       public class MyDaoTest {
         @ClassRule
         public static EmbeddedDatabaseRule rule = new EmbeddedDatabaseRule(
           new EmbeddedDatabaseBuilder()
             .generateUniqueName(true)
             .addScript("classpath:/sql/init.sql")
             .addScript("classpath:/sql/data.sql")
             .build()
         );
    
         @Test
         public void test1() throws Exception {
           Assert.assertEquals(2, count(rule.getDb().getConnection()));
         }
       }
     
    • Constructor Detail

      • EmbeddedDatabaseRule

        public EmbeddedDatabaseRule​(org.springframework.jdbc.datasource.embedded.EmbeddedDatabase db)
        Create rule.
        Parameters:
        db - Embedded database.
      • EmbeddedDatabaseRule

        public EmbeddedDatabaseRule()
        Create rule with default builder.
      • EmbeddedDatabaseRule

        public EmbeddedDatabaseRule​(Class<?> testClass)
        Create rule and lookup for EmbeddedDatabaseConfiguration in the testClass to initialize the embedded database.
        Parameters:
        testClass - The tested class.
    • Method Detail

      • before

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

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

        public org.springframework.jdbc.datasource.embedded.EmbeddedDatabase getDb()
        Gets currently created database instance.
        Returns:
        Database instance, may be null until rule has been initialized.