I have around 10 JUnit that will be executed automatically. I would like to reset the database in every of them. I have this piece of code:
//@Transactional
public class TestMediaObjectService extends AbstractDataAccessTest{
//This method reset the database, emptying the tables
@Test
public void testCreateDataBase() throws Exception {
TestDatabaseCreation creation = new TestDatabaseCreation();
creation.resetDatabase();
}
//This is one of the methods.
@Test
public void testStoreMediaObject() throws Exception {
//......
}
When I reset the database manually with the same script that I am using in the method testCreateDataBase and after that run this test (without that method), the tables are created automatically. But if I run the code as I have pasted above, that tables are not created, therefore I get this error:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table ‘one_table’ doesn’t exist
How could I run that method in every before running other methods in the test? The annotation @Transactional was removed, but error was still there.
Usually you don’t need to reset the database manually, because JUNIT does this for you before every test. Use these annotations:
Junit will rollback all transactions done in a test after running it. All you need is an existing empty database. If you use hibernate to manage your entities, you don’t even need to have the tables.
If you want to do it manually, use the
@Beforeannotation at a setup method:This will be run before every test.
If you want to setup your database tables once for all tests in a class, use
@BeforeClass. But usually that’s not best practice, as every test should be independent of any other test.