Search code examples
javaoracle-databaseunit-testingtestngin-memory-database

How to write in test case with in-memory-database?


I am using Oracle as my database, Spring Boot as my framework.

I don't know how to write a test case to check database query? I have heard that it is possible through In-Memory Database. But don't find a proper example.

Suppose in my code I have written a SQL query that SELECT * FROM tableName and it is returning me a ResultSet Object.

So in while writing test case how can I check that?

Every time I don't want to go into the database and fetch a query.

I know that is possible but my question is how can I replace my query's result with a dummy result which I will store in any file.

Thanks in advance


Solution

  • You should initialize your Hibernate SessionFactory with another hibernate config, that uses H2 in-memory database, example test-hibenate.properties:

    hibernate.dialect=org.hibernate.dialect.H2Dialect
    hibernate.connection.url=jdbc:h2:mem:orm
    javax.persistence.schema-generation.database.action=drop-and-create
    

    Then in your tests you can use your DAO's just in regular way.

    If you use plain JDBC, you can create connection to H2 in-memory database this way:

    Connection connection = DriverManager.getConnection("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1", "", "");
    

    And you will need H2 database dependency: https://mvnrepository.com/artifact/com.h2database/h2