Suppose I want to create and use an H2 database for my integration tests.
Maven has a command to run tests: mvn test
.
Is there a way to tell maven to start an H2 database server for the tests and stop it when it's done?
I imagine this working similar to how I can run tomcat via a Maven command (mvn tomcat:run
).
Sorry if this question is nonsensical, I'm still wrapping my head around new concepts.
Access the H2 Console You can access the console at the following URL: http://localhost:8080/h2-console/.
To access an in-memory database from another process or from another computer, you need to start a TCP server in the same process as the in-memory database was created. The other processes then need to access the database over TCP/IP or TLS, using a database URL such as: jdbc:h2:tcp://localhost/mem:db1 .
I was able to get it to work without using an external server just by adding the dependency to H2 via Maven and then using this bean:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.h2.Driver"/> <property name="url" value="jdbc:h2:file:h2\db"/> <property name="username" value="sa"/> <property name="password" value=""/> </bean>
Then again, this required that I use a file-based DB instead of in-memory. But it does the trick.
you can create 2 small classes with main methods that start and stop the database. the idea is to run the StartServer class before the integration tests are run and then class StopServer after the tests have run.
you should do the same for your DB server as described somewhere in this document (description is for starting and stopping Jetty in integration tests)
in your pom.xml you should define the maven-exec-plugin to run the exec:java goal and create 2 executions (1 for calling StartServer and 1 for StopServer):
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.1.1</version> <executions> <execution> <!-- start server before integration tests --> <id>start</id> <phase>pre-integration-test</phase> <goals> <goal>java</goal> </goals> <configuration> <mainClass>com.foo.StartServer</mainClass> </configuration> </execution> <execution> <!-- stop server after integration tests --> <id>stop</id> <phase>post-integration-test</phase> <goals> <goal>java</goal> </goals> <configuration> <mainClass>com.foo.StopServer</mainClass> </configuration> </execution> </executions> </plugin>
hope that's what you want
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