Maven: Having multiple @SpringBootTests causes H2:memory database to be set up multiple times when running mvn test

huangapple go评论76阅读模式
英文:

Maven: Having multiple @SpringBootTests causes H2:memory database to be set up multiple times when running mvn test

问题

我有几个使用了 @SpringBootTest 注解的测试。我的应用程序使用 H2 内存数据库,在每次应用程序运行时都会设置它。

当我通过我的集成开发环境(IDE)逐个运行每个测试用例时,所有用例都能正常工作。然而,当我运行 mvn test 时,我会收到 SQL 约束违规错误,因为显然我的应用程序尝试重新设置我的数据库(而数据已经存在,导致了错误)。

仅保留一个 @SpringBootTest 用例允许我成功运行 mvn test

我的问题是,我如何才能在运行 mvn test 时使所有测试都能运行,而不会尝试重新设置我的数据库?是否有一些我可以添加的注解来实现这一点?

或者是否有一种方法可以使测试在再次设置数据库之前等待数据被删除?

谢谢

英文:

I have several @SpringBootTest annotated tests. My app uses H2 in-memory database that gets set up each time the app runs.

When i run each test case individually through my IDE, all cases work. When i run mvn test however, i get SQL constraint violation errors because apparently my app is trying to set up my database again (and the data already exists, causing the errors).

Removing all @SpringBootTest cases except for one allows me to run mvn test successfully.

My question is, how do i make it so that i can run all the tests with mvn test without it trying to set up my database again? Is there some annotation that i can add for this?

Or is there a way to make the tests wait for the data to be dropped before setting it up again?

Thanks

答案1

得分: 3

在测试类和/或方法上使用@DirtiesContext注解。通过这样做,一旦测试完成,操纵的数据将被恢复。

链接:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html

英文:

Use @DirtiesContext annotation over test class(es) and/or method(s). With this the manipulated data get reverted back once that test completes.

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html

huangapple
  • 本文由 发表于 2020年8月18日 23:54:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/63472263.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定