Issue
I have an entity menu, with a child relationship Restaurant. I will to check if that there are restaurants with the Menu, the menu cannot be deleted, so I made this Junit Test:
Restaurant resto = new Restaurant(menu);
restaurantService.save(resto);
menuService.delete (menu);
menu = menuService.findByMenuId(menuName);
assertNotNull (menu);
but of course I can't test this UserCase because I have this Exception:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
public class Menu {
...
@OneToMany(mappedBy = "menu",
cascade = CascadeType.ALL,
orphanRemoval = true, fetch = FetchType.LAZY)
@JsonIgnore
private Set<Restaurants> restaurant = new HashSet<>();
...
}
and
public class Restaurant {
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "menu_id")
@JsonIgnore
private Menu topMenu;
..
}
Solution
In such cases, assert statements won't help. You need to use "expected" in order to check that deletion doesn't happen and exception is thrown.
@Test(expected=MySQLIntegrityConstraintViolationException.class)
public void testMenuDeletionFailure() {
\\invoke the method you need to unit test, there is no need of assertion statements
}
Try this..
Answered By - codeLover