2011-07-21 8 views
0

私は間違っていると分かっているテストを書いています。 originalProductとupdatedProductの同じインスタンスを取得して、updatedProduct.setProductName("Updated Product Name");と呼び出すと、originalProductとupdatedProductの両方のproductNameメンバーが更新されるようになります。これを変更して、このオブジェクトの2つの異なるインスタンスを得ることができます。Spring JUnitテストでHibernateと別のインスタンスを取得する方法

@Test 
@Transactional 
public void testUpdateProduct() { 
    productDao.addProduct(createTempProduct()); 
    Product originalProduct = productDao.getProduct((long)999); 
    Product updatedProduct = productDao.getProduct((long)999); 

    updatedProduct.setProductName("Updated Product Name"); 
    productDao.updateProduct(updatedProduct); 
    Product newProduct = productDao.getProduct((long)999); 
    Assert.assertNotSame(originalProduct, newProduct); 
    Assert.assertSame(updatedProduct, newProduct); 
} 
+0

これは、 'productDao.getProduct()'が何をするかを知るのに役立ちます –

答えて

3

あなたはHibernateのfirst-level cacheを打っています。つまり、テストのスコープ内でproductDao.getProduct(999)を呼び出すたびに同じProductインスタンスが返されます。これは、初めてロードするときにインスタンスをSessionに格納するためです。これを回避するには、セッションのevict the specific objectまたはセッションのclear all objectsのいずれかをコール間で行うことができます。

0

new Productを作成し、DB製品からすべての値を取得し、それらの値を新しいオブジェクトに設定します。それで、少なくとも値の点で、元のオブジェクトの欺瞞です。

関連する問題