代码之家  ›  专栏  ›  技术社区  ›  en Peris

JUnit:测试父子实体

  •  0
  • en Peris  · 技术社区  · 7 年前

    我有一个实体菜单,有一个儿童关系餐厅。我会检查是否有餐厅有菜单,菜单不能删除,所以我做了这个junit测试:

        Restaurant resto = new Restaurant(menu);
        restaurantService.save(resto);
    
                menuService.delete  (menu);
    
                menu = menuService.findByMenuId(menuName);
    
    assertNotNull (menu);
    

    但是我当然不能测试这个用户案例,因为我有这个例外:

    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;
    ..
    }
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   codeLover Sumit Tyagi    7 年前

    在这种情况下,断言语句没有帮助。您需要使用“expected”来检查删除是否不会发生以及是否引发异常。

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

    试试这个……