gpt4 book ai didi

java - Junit:测试父子实体

转载 作者:行者123 更新时间:2023-12-02 11:05:14 24 4
gpt4 key购买 nike

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

试试这个..

关于java - Junit:测试父子实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51020908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com