Write some usual tests for my MVC webapp and stopped at findById() testing. My model classes:
@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;
And my test code:
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);
}
Well, assertion failed, because of difference product.category.products and product.supplier.products properties, as you can see on pic:
One product have it as null, another as {PersistentBag}.
Sure I can easy hack it by writing custom equals method (which will ignore these properties), but sure it's not the best way.
So, why these fields are different? I'm sure solution in properly annotation of entities fields.