ドメイン オブジェクトの挿入を行うテスト ケースがあります。ドメインオブジェクト内で、フィールド「deploymentType」の1つが設定されていない場合、postgresにはデフォルトがあり、本番として入力されます。
これをSpring単体テストでテストしたいのは、deploymentTypeをnullに設定して挿入し、postgresがそれを処理すると、デフォルトが設定されます。
私のテストケースは AbstractTransactionalTestNGSpringContextTests を拡張し、注釈が付けられています
@Transactional(propagation = Propagation.NESTED)
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
単体テストケースは以下の通りです。
@Test
public void createCustomerWithSite() {
this.customerService.createCustomerSite(TestData.makeCustomerSite(this.customer, "test-alias"));
final List<CustomerSite> list = this.customerService.findCustomerSites(this.customer.getId());
assertThat(list.size(), is(1));
final CustomerSite cs = list.get(0);
assertThat(cs.getClusterDeploymentType(), is(ClusterDeploymentType.PRODUCTION));
}
テストはトランザクションであるため、コミットは行われないため、ドメイン オブジェクトに戻ると、「deploymentType」が null であり、テストが失敗します。
そのような場合、単体テストでデータベースの動作をテストしたい場合は、テストの途中で transactionManager にアクセスし、トランザクションをコミットする必要があると思います。新しいトランザクションを開始し、db からドメイン オブジェクトを取得してから、挿入中に db によってデフォルト値が設定されているかどうかを確認します。
お気に入り :
this.customerService.createCustomerSite(TestData.makeCustomerSite(this.customer, "test-alias"));
TransactionManager tm = getTransactionManager();
tm.commit(); // the default type will be insterted in db and be visible in next transaction.
tm.beginTransaction();
final List<CustomerSite> list = this.customerService.findCustomerSites(this.customer.getId());
assertThat(list.size(), is(1));
final CustomerSite cs = list.get(0);
assertThat(cs.getClusterDeploymentType(), is(ClusterDeploymentType.PRODUCTION));
トランザクションの単体テストでトランザクション マネージャーにアクセスするにはどうすればよいですか。これは正しい方法ですか?