我有一个测试类来测试 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/