基於內存和測試

現在是最有趣的。在測試 Hibernate 代碼時,通常您不想使用真正的基礎,而是使用某種實現最少功能的存根。

您能想像一個實現大部分 SQL Server 標準的存根嗎?我沒有。但是,內存數據庫本身就非常出色。它的工作原理大致是這樣的:

  • 在@BeforeAll 方法中,我們初始化內存中的數據庫連接。
  • 在@BeforeEach 方法中,我們獲取會話並打開一個事務。
  • 在@Test 方法中,我們使用當前會話和事務。
  • 在@AfterEach 方法中,我們提交事務。
  • 最後,在 AfterAll 方法中,我們關閉與數據庫的連接。

以下是測試準備工作的樣子:

@Test
public class HelloTest {
  private static SessionFactory sessionFactory = null;
  private Session session = null;

  @BeforeAll
  static void setup(){
    try {
  	StandardServiceRegistry standardRegistry  = new StandardServiceRegistryBuilder()
      	.configure("hibernate-test.cfg.xml").build();

  	Metadata metadata = new MetadataSources(standardRegistry)
      	.addAnnotatedClass(Employee.class)
      	.getMetadataBuilder()
      	.build();

      sessionFactory = metadata.getSessionFactoryBuilder().build();

    } catch (Throwable ex) {
        throw new ExceptionInInitializerError(ex);
    }
  }

  @BeforeEach
  void setupThis(){
      session = sessionFactory.openSession();
      session.beginTransaction();
  }

  @AfterEach
  void tearThis(){
      session.getTransaction().commit();
  }

  @AfterAll
  static void tear(){
      sessionFactory.close();
  }

這就是測試本身在 Hibernate 的作用下的樣子:

@Test
public class HelloTest {

  @Test
  void createSessionFactoryWithXML() {
       Employee emp = new Employee();
       emp.setEmail("demo-user@mail.com");
       emp.setFirstName("demo");
       emp.setLastName("user");

       Assertions.assertNull(emp.getEmployeeId());
       session.persist(emp);
       Assertions.assertNotNull(emp.getEmployeeId());
  }
}

測試數據

您還可以使用測試數據填充測試數據庫。

通常為此製作兩個sql文件:

  • schema.sql 包含一個在數據庫中創建表的腳本
  • test-data.sql 包含一個用測試數據填充表的腳本

表創建和測試數據通常被分離到不同的文件中,因為他們自己的測試數據組幾乎總是出現在不同的測試組中。

執行這些文件如下所示:

void runSqlScriptFile(String filePath){
  	String sqlScript = new String( Files.readAllBytes(Paths.get(filePath)) );
  	Session session = sessionFactory.openSession();
      Query query = session.createNativeQuery("BEGIN " + sqlScript + " END;");
      query.executeUpdate()
}

你的設置方法會有所改變:

@BeforeAll
static void setup(){
  try {
	StandardServiceRegistry standardRegistry  = new StandardServiceRegistryBuilder()
    	.configure("hibernate-test.cfg.xml").build();

	Metadata metadata = new MetadataSources(standardRegistry)
    	.addAnnotatedClass(Employee.class)
    	.getMetadataBuilder()
    	.build();

	sessionFactory = metadata.getSessionFactoryBuilder().build();
	runSqlScriptFile(“scema.sql”);
	runSqlScriptFile(“test-data.sql”);

  } catch (Throwable ex) {
      throw new ExceptionInInitializerError(ex);
  }
}