java - 仅运行一次 junit 设置方法

标签 java junit spring-data-jpa

我有一个测试类来测试 JPA 存储库的一些功能,我的 JPA 存储库与 H2 数据库连接,我想用我的测试实体填充我的数据库,但我只需要在所有测试之前做一次,这是我的测试类:

public class EntityRepositoryTest {

    @Autowired
    EntityJPARepository EntityRepo;

    Entity entity;

    @Before
    public void setup(){
         entiti = //initializes entity with values
         EntityRepo.save(entiti);
    }    

    //some tests on repo

 }

问题是 @Before 注释在每个测试方法之前调用它,我不希望我的实体对象在 H2 db 中重复(因为 save 将在之前调用每个方法),我也不能使用注释 @BeforeClass 因为我需要调用 @autowired 存储库上的 save 方法。我如何才能在所有测试之前仅调用一次设置,但在存储库 Autowiring 之后仍然调用?

最佳答案

您可以使用@Before 方法,您只需要做一些检查:

public class EntityRepositoryTest {

    @Autowired
    EntityJPARepository EntityRepo;

    Entity entity;

    @Before
    public void setup() {
         if (entity == null) { // true only for first pass
             entity = //initializes entity with values
             EntityRepo.save(entity);
         }
    }    

    //some tests on repo

 }

或者,您可以添加一个删除实体的 @After 方法。

关于java - 仅运行一次 junit 设置方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39144319/

相关文章:

java - 添加到 hashmap 和 arraylist

java - Java中的隐式 super 接口(interface)?

java - 从 Java 8 中的方法返回 Lambda?

java - 很简单 : 1/20 returns 0. 0

java - 如何使用 archunit 验证方法注释是否使用具有特定值的属性

java - 同时使用 junit 断言和 mockito 验证

java - 源文件夹不在 java 构建类路径上,使用 JUnit

java - 使用 spring data JPA 和 spring boot 无法在 View 中访问数据库数据

spring - 如何创建 URL slug 扩展?

mongodb - 使用 2 个数据库时的 Javers ENTITY_INSTANCE_WITH_NULL_ID