英文:
test Junit deleteById doesn't pass if id is not present
问题
我正在进行一些 JUnit 测试以改进我的应用程序。其中一个测试涉及删除单个行(通过作为主键的 id 表示),如果存在,则运行正常。现在我正在测试如果我想删除在我的数据库中不存在的 id 时,我的应用程序的行为。
我期望的是,我的测试通过,受影响的行数为 0,但实际上它未通过,显示以下错误:
不存在 id 为 326L 的 com.package1.package2.package3.entities.className 实体!
有什么建议吗?
英文:
I'm doing some junit tests to improve my application. One of these, tests the deletion of a single raw (indicated by an id as primary key) if present, and this works fine. Now I'm testing how my application behave if I want to delete an id Not present in my database.
What I expect is that my test passes with 0 rows affected, but he doesn't pass giving me this error:
> No class com.package1.package2.package3.entities.className entity with id 326L exists!
Some advice?
答案1
得分: 1
deleteById()
方法首先尝试按照 Id
查找实体。
如果找不到任何实体,则会抛出异常;您可以拥有自己的仓库并声明 deleteAllByIdIn()
方法,该方法以 id 集合作为参数,ORM 将为您创建其实现。
通过这种方式,即使不存在具有这些 id 的实体,您也不应该收到任何异常。或者您总是可以创建一个通过 id 在数据库中删除行的原生 SQL 查询。
英文:
deleteById()
from CrudRepository
firstly tries to find entity by Id
.
In case no entity is found it throws exception; You can have your own repository and declare deleteAllByIdIn()
method which takes collection of ids as argument and ORM will create its implementation for you.
This way you should not get any exceptions even if entities with such ids were not present. Or you can always make a native SQL query that deletes the row in DB by id.
答案2
得分: 0
解决方案:
方法应为:
@Query (你的查询语句, nativeQuery=true)
@Modifying
@Transactional
void DeleteById(@Param(id) Long id)
英文:
SOLUTION:
The method should be :
@Query (your query, nativeQuery=true)
@Modifying
@Transactional
void DeleteById(@Param(id) Long id)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论