Junit with HSQL / H2 without Spring / Sleep

I am trying to use H2 or HSQL for my unit testing. But my application is not from spring and sleep mode. It looks like most links are only with spring and sleep mode for HSQL / H2 in db memory for unit testing.

Can someone point out the correct link where only hsql / h2 is used with junit? Appreciate your time.

+4
source share
2 answers

I usually do something like this:

In the @Before method, I establish a connection to the memory database, something like this:

@Before public void setup() { this.dbConnection = DriverManager.getConnection("jdbc:hsqldb:mem:testcase;shutdown=true", "sa", null); } 

The connection is stored in an instance variable, so it is available for each test.

Then, if all tests use the same tables, I also create them inside the setup () method, otherwise each test creates its own tables:

 @Test public void foo() { Statement stmt = this.dbConnection.createStatement(); stmt.execute("create table foo (id integer)"); this.dbConnection.commit(); ... now run the test } 

In the @After method, I simplify the connection, which means that the database in memory is cleared and the following test runs with a clean version:

 @After public void tearDown() throws Exception { dbConnection.disconnect(); } 

Sometimes I need to run unitt-tests again on a real database server (you cannot test Postgres or special Oracle functions using HSQLDB or H2). In this case, I establish the connection only once for each Testclass, and not once for each test method. Then I have methods to delete all objects to clear the circuit.

All this can be placed in a small utility class to avoid partial code. Apache DbUtils can also make life easier, as well as DbUnit, if you want to somehow squeeze out test data.

+10
source

I know I'm a little late to the party :-)

I had the same problem and I created a JUNIT integration that uses the @Rule mechanism to tune the in-memory database for JUnit tests. I found this to be a very simple and convenient way to test my database integration code. Feedback is more than welcome.

Source code and usage instructions can be found at https://github.com/zapodot/embedded-db-junit

0
source

Source: https://habr.com/ru/post/1488202/


All Articles