Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

running setup method for junit only once

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?

like image 673
Akka Jaworek Avatar asked Mar 27 '26 11:03

Akka Jaworek


1 Answers

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.

like image 71
Miloš Milivojević Avatar answered Apr 02 '26 21:04

Miloš Milivojević