インメモリデータベースを使用した自己完結型テスト
1. 概要
このチュートリアルでは、create a simple Spring application which relies on an in-memory database for testingに進みます。
標準プロファイルの場合、アプリケーションにはスタンドアロンのMySQLデータベース構成があります。これには、適切なユーザーとデータベースをセットアップして、MySQLサーバーをインストールして実行する必要があります。
アプリケーションのテストを容易にするために、MySQLに必要な追加の構成を省略し、代わりにH2インメモリデータベースを使用してJUnitテストを実行します。
2. Mavenの依存関係
開発には、次の依存関係が必要です。
org.springframework
spring-test
4.3.7.RELEASE
org.springframework.data
spring-data-jpa
1.11.1.RELEASE
com.h2database
h2
1.4.194
org.hibernate
hibernate-entitymanager
5.2.9.Final
spring-test、spring-data-jpa、h2、およびhibernate-entitymanagerの最新バージョンは、MavenCentralからダウンロードできます。
3. データモデルとリポジトリ
エンティティとしてマークされる単純なStudentクラスを作成しましょう。
@Entity
public class Student {
@Id
private long id;
private String name;
// standard constructor, getters, setters
}
次に、Spring DataJPAに基づいてリポジトリインターフェースを作成しましょう。
public interface StudentRepository extends JpaRepository {
}
これにより、SpringはStudentオブジェクトを操作するためのサポートを作成できるようになります。
4. 個別のプロパティソース
標準モードとテストモードで異なるデータベース構成を使用できるようにするために、アプリケーションの実行モードによって場所が異なるファイルからデータベースプロパティを読み取ることができます。
For normal mode, the properties file will reside in src/main/resources, and for the testing method, we will use a properties file in the src/test/resources folder。
テストを実行すると、アプリケーションは最初にsrc/test/resourcesフォルダー内のファイルを探します。 この場所にファイルが見つからない場合は、src/main/resourcesフォルダーで定義されているファイルが使用されます。 ファイルが存在する場合はtestパスである場合、mainパスからのファイルをオーバーライドします。
4.1. プロパティファイルの定義
MySQLデータソースのプロパティを定義するsrc/main/resourcesフォルダーにpersistence-student.propertiesファイルを作成しましょう。
dbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/myDb
jdbc.user=tutorialuser
jdbc.pass=tutorialpass
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=create-drop
上記の構成の場合、myDbデータベースを作成し、tutorialuser/tutorialpassユーザーを設定する必要があります。
テストにはインメモリデータベースを使用するため、src/test/resourcesフォルダーに同じ名前の同様のファイルを作成します。このファイルには、同じキーとH2データベース固有の値を持つプロパティが含まれています。
jdbc.driverClassName=org.h2.Driver
jdbc.url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1
hibernate.dialect=org.hibernate.dialect.H2Dialect
hibernate.hbm2ddl.auto=create
H2データベースをメモリ内に配置して自動的に作成し、JVMが終了すると閉じて削除するように構成しました。
4.2. JPAの構成
プロパティソースとしてpersistence-student.propertiesというファイルを検索し、その中で定義されているデータベースプロパティを使用してDataSourceを作成する@Configurationクラスを作成しましょう。
@Configuration
@EnableJpaRepositories(basePackages = "org.example.persistence.dao")
@PropertySource("persistence-student.properties")
@EnableTransactionManagement
public class StudentJpaConfig {
@Autowired
private Environment env;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.user"));
dataSource.setPassword(env.getProperty("jdbc.pass"));
return dataSource;
}
// configure entityManagerFactory
// configure transactionManager
// configure additional Hibernate Properties
}
5. JUnitテストの作成
上記の構成に基づいて、StudentRepositoryを使用してStudentエンティティを保存および取得する簡単なJUnitテストを作成しましょう。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
classes = { StudentJpaConfig.class },
loader = AnnotationConfigContextLoader.class)
@Transactional
public class InMemoryDBTest {
@Resource
private StudentRepository studentRepository;
@Test
public void givenStudent_whenSave_thenGetOk() {
Student student = new Student(1, "john");
studentRepository.save(student);
Student student2 = studentRepository.findOne(1);
assertEquals("john", student2.getName());
}
}
Our test will run in an entirely self-contained manner —ログに示されているように、メモリ内のH2データベースを作成し、ステートメントを実行してから、接続を閉じてデータベースを削除します。
INFO: HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
Hibernate: drop table Student if exists
Hibernate: create table Student (id bigint not null, name varchar(255), primary key (id))
Mar 24, 2017 12:41:51 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hiber[email protected]1b8f9e2'
Hibernate: select student0_.id as id1_0_0_, student0_.name as name2_0_0_ from Student student0_ where student0_.id=?
Hibernate: drop table Student if exists
6. 結論
この簡単な例では、インメモリデータベースを使用して自己完結型のテストを実行する方法を示しました。
いつものように、完全なソースコードはover on GitHubで見つけることができます。