I have a test class to test some functions of JPA repositories, my JPA repositories are connected with H2 db, i want to populate my db with my test entites but i need to do it only once before all tests, this is my test class:
public class EntityRepositoryTest {
@Autowired
EntityJPARepository EntityRepo;
Entity entity;
@Before
public void setup(){
entiti = //initializes entity with values
EntityRepo.save(entiti);
}
//some tests on repo
}
the problem is that @Before annotiation calls it before every test method, and i dont want my entity object to duplicate in H2 db (since save will be called before every method), i also cant do in with annotation @BeforeClass since i need to call save method on @autowired repository. How can i call Setup only once before all tests but stil after repository gets autowired?
You can use the @Before method, you just need a bit of checking to do:
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
}
Alternatively, you can add an @After method that deletes the entity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With