記憶とテストのベース

そして今、最も興味深い。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());
  }
}

テストデータ

テスト データベースにテスト データを入力することもできます。

通常、このために 2 つの 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);
  }
}