JUnit test starts before H2´s RUNSCRIPT finishes JUnit test starts before H2´s RUNSCRIPT finishes database database

JUnit test starts before H2´s RUNSCRIPT finishes


I suspect this is a race condition. According to the documentation the script is executed for every single client that connects to the database. Since you are always dropping the Weather table before recreating it, it might happen that when a test A is already running and a second client B connects to the database, the table gets drop right under the nose of A. B might be another test that runs in parallel or a second thread in the same test.

If that is the case, you might try to use the RunScript tool in your manualCreateDataSource() method instead of the INIT parameter in the JDBC connection URL:

String jdbcUrl = "jdbc:h2:mem:WeatherAPI;MODE=MySQL;DB_CLOSE_ON_EXIT=TRUE;TRACE_LEVEL_SYSTEM_OUT=1;"RunScript.execute(jdbcUrl, sa, "", "src/test/resources/sql/weatherapi.sql", null, false);

Additionally, you need to make getDs() thread-safe, by adding synchronized to it or better yet, by initializing the instance variable ds statically:

private static java.sql.DataSource ds = manualCreateDataSource();public static DataSource getDs() {    return ds;}


The answer from hzpz in fact help me see what was happening: race conditions. The question I entered did not specify that I am using maven (I apologize for that), and I found out that maven surefire plugin was forking the tests, thus the race condition in fact appeared. I decide to turn off forking and configured maven-surefire plugin in this way:

<plugin>    <groupId>org.apache.maven.plugins</groupId>    <artifactId>maven-surefire-plugin</artifactId>    <configuration>        <forkCount>1</forkCount>        <reuseForks>false</reuseForks>    </configuration></plugin>

There are several questions regarding the forking, but none relating H2's RUNSCRIPT with the race conditions.

Here more details on surefire plugin:

Maven Surefire Plugin - Class loading and forking