我有一个实体菜单,带有一个与孩子有关系的餐厅。我将检查是否有带有菜单的餐厅,无法删除菜单,因此我进行了Junit测试:

    Restaurant resto = new Restaurant(menu);
    restaurantService.save(resto);

            menuService.delete  (menu);

            menu = menuService.findByMenuId(menuName);

assertNotNull (menu);


但我当然不能测试此UserCase,因为我有以下异常:

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<>();
...
}




public class Restaurant {

@ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "menu_id")
    @JsonIgnore
    private Menu topMenu;
..
}

最佳答案

在这种情况下,断言语句将无济于事。您需要使用“ expected”来检查是否不会发生删除并引发异常。

@Test(expected=MySQLIntegrityConstraintViolationException.class)
public void testMenuDeletionFailure()    {
\\invoke the method you need to unit test, there is no need of assertion statements
}


尝试这个..

10-07 19:27