2016-09-16 283 views
0

爲我的MVC webapp編寫一些常用測試,並停止在findById()測試。 我的模型類:如何正確註釋休眠實體

@Entity 
public class Product { 
    @Id 
    @GeneratedValue (strategy = GenerationType.IDENTITY) 
    private Long id; 

    private String name; 

    private String description; 

    private double purchasePrice; 

    private double retailPrice; 

    private double quantity; 

    @ManyToOne 
    @JoinColumn (name = "supplier_id") 
    private Supplier supplier; 

    @ManyToOne 
    @JoinColumn (name = "category_id") 
    private Category category; 

@Entity 
public class Category { 
    @Id 
    @GeneratedValue (strategy = GenerationType.IDENTITY) 
    private Long id; 

    private String name; 

    private String description; 

    @LazyCollection(LazyCollectionOption.FALSE) 
    @OneToMany 
    @Cascade(org.hibernate.annotations.CascadeType.ALL) 
    private List<Product> products; 

@Entity 
public class Supplier { 
    @Id 
    @GeneratedValue (strategy = GenerationType.IDENTITY) 
    private Long id; 

    private String name; 

    @LazyCollection(LazyCollectionOption.FALSE) 
    @Cascade(org.hibernate.annotations.CascadeType.ALL) 
    @OneToOne 
    private Contact contact; 

    @LazyCollection(LazyCollectionOption.FALSE) 
    @OneToMany 
    private List<Product> products; 

我的測試代碼:

private Product productTest; 
private Category categoryTest; 
private Supplier supplierTest; 

@Before 
public void setUp() throws Exception { 
    categoryTest = new Category("Test category", "", null); 
    supplierTest = new Supplier("Test supplier", null, null); 
    productTest = new Product("Test product","", 10, 20, 5, supplierTest, categoryTest); 

    categoryService.save(categoryTest); 
    supplierService.save(supplierTest); 
    productService.save(productTest); 
} 

@Test 
public void findById() throws Exception { 
    Product retrieved = productService.findById(productTest.getId()); 
    assertEquals(productTest, retrieved); 
} 

好,斷言失敗,因爲差異product.category.products和product.supplier.products屬性,你可以看到圖: enter image description here 一個產品將其作爲null,另一個作爲{PersistentBag}。 當然,我可以通過編寫自定義equals方法(它將忽略這些屬性)輕鬆破解它,但確定它不是最好的方法。

那麼,爲什麼這些領域不同? 我確定在實體字段的正確註解中的解決方案。

回答

1

兩個指針:

  • 你用在你的關係領域@LazyCollection(LazyCollectionOption.FALSE),所以與註釋字段動態地通過你的ORM加載當你檢索你的實體,而entites的在你的單元測試的夾具創建外部創建來自你的ORM,你不重視這些領域。
  • 即使你刪除了@LazyCollection(LazyCollectionOption.FALSE),如果你想用一個檢索到的實體和一個手工創建的實體來執行assertEquals(),你可能會有其他區別。例如,使用Hibernate,您的懶惰List將不會是null,而是PersistentList的實例。

所以,你應該執行一些工作來執行斷言。
您可以單獨檢查屬性,也可以使用反射來斷言字段並忽略預期對象中空字段的比較。

查看http://www.unitils.org/tutorial-reflectionassert.html,它可能會幫助你。