Issue
I am working on a legacy project which is build on purely Java/J2EE servlets. No spring and other frameworks. It is built on ant. Now I want to integrate junit with my project, I am able to integrate but I want to mock the DB and run the test cases in the mocked DB connection. I think in spring boot we can easily do that with H2 database. But only challenge I am facing is we are not using spring boot. I am able to mock the functions and run the test cases but what I need is to mock the full database and run the test classes on my mocked database. Any leads how I can achieve this or it is feasible or not?
Solution
You can run h2 database
in pure java
since it is written in it. See H2 Documentation.
Start h2 database
server in pure java and run sql
script
To start a tcp-server you can use a
Server
tool:Server server = Server.createTcpServer(); server.start();
To to start also a web-server (with
h2-console
) you can add:Server server = Server.createWebServer(); server.start();
To open
JdbcConnection
andRunScript
you can write something like this:private void createTables(String url, String username, String password, File script) throws SQLException, IOException { Properties info = new Properties(); info.put("user", username); info.put("password", password); JdbcConnection connection = new JdbcConnection(url, info); InputStreamReader reader = new InputStreamReader(new FileInputStream(script)); RunScript.execute(connection, reader); reader.close(); connection.close(); }
See also:
- How to enable h2-console in spring-webmvc without spring-boot?
- Setting up in-memory H2 database without Spring Boot
- Executing script file in h2 database
Answered By - user8280225