【问题标题】:Junit: Testing Parent child entitiesJunit:测试父子实体
【发布时间】:2018-06-25 10:07:38
【问题描述】:

我有一个实体菜单,有一个子关系餐厅。我会检查菜单是否有餐厅,菜单不能删除,所以我做了这个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;
..
}

【问题讨论】:

  • 你能告诉我们你的实体吗?

标签: java jpa junit spring-data-jpa spring-data


【解决方案1】:

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

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

试试这个..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 2022-01-23
    • 2016-10-31
    • 1970-01-01
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    相关资源
    最近更新 更多