3

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

Sharvil
  • 247
  • 1
  • 6
  • 15
  • Read the docs? What have you tried? – Mike Tung Mar 17 '18 at 14:08
  • I think you can create an initial SQL script and fill in your in-memory database (like H2 for example) in @Before block of your unit test. It helps you to know current actual state of you database. You can modify this initial script with improvement of you domain model. – MrFroll Mar 17 '18 at 14:20
  • You can find this useful https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html#howto-initialize-a-database-using-hibernate – MrFroll Mar 17 '18 at 14:27
  • 1
    Probably Your answer [In memory DB](https://stackoverflow.com/a/66259759/410439) – Ravi Parekh Sep 15 '21 at 13:30

1 Answers1

3

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

Michal Lonski
  • 877
  • 1
  • 11
  • 20