SlideShare a Scribd company logo
1 of 14
In-Memory Unit Tests
with Apache DbUnit &
HSQL DB
Presented By Sabir Khan
Agenda
 In Memory Unit Testing - Need
 In Memory Unit Testing - Architecture
 In Memory Unit Testing – Tools Needed
 In Memory Unit Testing – Steps
 In Memory Unit Testing – Code Samples
 In Memory Unit Testing – Challenges
 Thanks
In Memory Unit Testing - Need
• Unit Tests might be required to run at following stages – during code development,
code integration, build creation and might be at deployment time too.
• During Development – Tests have to be very fast – should take less than 5 seconds
due to frequent runs of tests and that frequent code changes didn’t break anything else
• As far as unit testing is concerned, setting up connection with actual DB and running
actual queries etc. is very slow
• In-Memory testing is better than no testing at all – since we generally mock db
connection objects etc. and don’t write unit tests for DAO Layer at all while generally
there is too much code and logic at DAO layer too
• During deployments – unit tests are run before starting of the application or other
system components so DB might not be available or we don’t expect DB to be
available for unit test runs
In Memory Unit Testing – Need…Contd..
• If unit tests fail due to DB not being available – it would still be counted as a failure and
deployment might not proceed
• Tests can be run on systems that don’t have connectivity to real databases which is
generally the case for build boxes
• Tests are run on consistent data because data resides in checked in xml files. With
actual DB, we will have to prepare data on all developer systems.
• Parallel Test Execution – Each test can have its own In – memory database so tests
can be run in parallel as far as data is concerned. DB locking and other contentious
issues will not occur
• With Maven, it has become easy to run unit tests and there are projects where
successful run of unit tests during deployments is a Go – No GO factor for production
deployments – if unit tests fail, deployment is a No GO
In Memory Unit Testing – Need…Contd..
• Using actual DB for unit tests might corrupt the test data because that is usually meant
for integration tests
• Code Coverage – If organization mandates a certain percentage of code coverage for
unit tests, DAO code can’t be left without unit tests as it might not be possible to
achieve desired coverage leaving DAO layer code. Mocking Connection etc. results in
very fake kind of unit tests with no value and there is no use of achieving code
coverage just for the sake of formality
In-Memory Unit Testing - Architecture
In-Memory Unit Testing – Tools Needed
 First, you need a database which supports In – Memory mode i.e. full db gets loaded in
memory, tables & data are created in memory and all these run time structures vanish once
tests finish. Nothing persists on disk. H2 , HSQL and MySQL databases support in-memory
mode. I used HSQLDB for my project and this presentation
 Secondly, You need an API to Connect to In-Memory database, table creation , preparing and
loading of data. I used Apache DBUnit for this - dbunit-2.4.9.jar
 Then you need a Unit Testing Framework like JUnit etc.
 So you will write unit tests in JUnit, connecting to in – memory database ( which is equivalent
to your real RDBMS ) for your data needs
In-Memory Unit Testing – Steps
 Include HSQL DB Jar to your project in any way suitable to you
 Use below values for connection string,
private static final String JDBC_DRIVER = org.hsqldb.jdbcDriver.class.getName();
private static final String JDBC_URL ="jdbc:hsqldb:mem:tests";
private static final String USER = "sa";
private static final String PASSWORD = "";
User and Password are fixed and notice URL’s :mem: portion which indicates in –
memory mode.
Include Apache DbUnit and JUnit dependencies to your project
In-Memory Unit Testing – Code Samples…Java
As illustrated in code sample, we create DB connection & db tables at @BeforeClass time and set up data at @Before time.
Public class TestClass{
private static final String JDBC_DRIVER = org.hsqldb.jdbcDriver.class.getName();
private static final String JDBC_URL ="jdbc:hsqldb:mem:tests";
private static final String USER = "sa";
private static final String PASSWORD = "";
private static IDatabaseTester databaseTester;
private IDataSet dataSet1,dataSet2;
@BeforeClass
public static void inMemDBSetUp() throws Exception{
databaseTester=new JdbcDatabaseTester(JDBC_DRIVER,JDBC_URL,USER,PASSWORD);
Connection connection=databaseTester.getConnection().getConnection();
createTables(connection);
}
@AfterClass
public static void inMemDbCleanUp(){}
…….contd…
In-Memory Unit Testing – Code Samples…Java..Contd
@Before
public void testDataSetUp() throws Exception{
service=new Service() ; //assume this is your service class to be tested
service.setDBConnection(databaseTester.getConnection().getConnection());
dataSet1=readDataSet1();
cleanlyInsert(dataSet1);
dataSet2=readDataSet2(); etc
cleanlyInsert(dataSet2);
}
In-Memory Unit Testing – Code Samples…Java..Contd
private static void createTables(Connection connection){
//Here we use connection object to create tables, table constraints etc like in real DB
//This will be very similar to plain jdbc code where your prepare statements from SQLS and execute those statements
}
//This method will read data table data kept in XML file and will pass on to cleanlyInsert method
private IDataSet readDataSet1() throws Exception {
return new FlatXmlDataSetBuilder().build(TestClass.class.getResourceAsStream("/data.xml"));
}
//similarly readDataSet2() method etc
//this method will load data into tables
private void cleanlyInsert(IDataSet dataSet) throws Exception {
databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
databaseTester.setDataSet(dataSet);
databaseTester.onSetup();
}
}//end testclass
In-Memory Unit Testing – Code Samples…XML data
 Data read in Java class resides in XML files in below format, data.xml
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<TABLE_NAME COLUMN_1=VALUE1, COLUMN2=VALUE2 …/>
</dataset>
Each row in above xml represents a single row in mentioned table at start of tag.
Similarly, a second row can be added for another table and so on…
In-Memory Unit Testing – Challenges
 First challenge that I faced is the syntax differences between actual database system
and HSQLDB so there might be quite a bit of effort required for creation of DDL
queries like CREATE TABLE statement etc.
 Schema Definition: I found it very hard to include schema name in data xml. I didn’t
found a way out for that.
Thank You !!
Thank You !!

More Related Content

What's hot (19)

JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
JDBC
JDBCJDBC
JDBC
 
Jdbc
JdbcJdbc
Jdbc
 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Jdbc[1]
Jdbc[1]Jdbc[1]
Jdbc[1]
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 
JDBC Java Database Connectivity
JDBC Java Database ConnectivityJDBC Java Database Connectivity
JDBC Java Database Connectivity
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
DataBase Connectivity
DataBase ConnectivityDataBase Connectivity
DataBase Connectivity
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Testing database content with DBUnit. My experience.
Testing database content with DBUnit. My experience.Testing database content with DBUnit. My experience.
Testing database content with DBUnit. My experience.
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
 

Similar to In Memory Unit Testing with Apache DbUnit

Database continuous integration, unit test and functional test
Database continuous integration, unit test and functional testDatabase continuous integration, unit test and functional test
Database continuous integration, unit test and functional testHarry Zheng
 
Automated Testing with Databases
Automated Testing with DatabasesAutomated Testing with Databases
Automated Testing with Databaseselliando dias
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionMazenetsolution
 
Building a Testable Data Access Layer
Building a Testable Data Access LayerBuilding a Testable Data Access Layer
Building a Testable Data Access LayerTodd Anglin
 
JDBC Connectivity Model
JDBC Connectivity ModelJDBC Connectivity Model
JDBC Connectivity Modelkunj desai
 
Writing better tests for your java script app
Writing better tests for your java script appWriting better tests for your java script app
Writing better tests for your java script appJakeGinnivan
 
SELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdfSELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdfEric Selje
 
java.pptx
java.pptxjava.pptx
java.pptxbfgd1
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5Smita B Kumar
 
Test studiowebinaraugcodedstep
Test studiowebinaraugcodedstepTest studiowebinaraugcodedstep
Test studiowebinaraugcodedstepDhananjay Kumar
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part ISivaSankari36
 

Similar to In Memory Unit Testing with Apache DbUnit (20)

Database continuous integration, unit test and functional test
Database continuous integration, unit test and functional testDatabase continuous integration, unit test and functional test
Database continuous integration, unit test and functional test
 
Automated Testing with Databases
Automated Testing with DatabasesAutomated Testing with Databases
Automated Testing with Databases
 
Dao example
Dao exampleDao example
Dao example
 
Integration testing - A&BP CC
Integration testing - A&BP CCIntegration testing - A&BP CC
Integration testing - A&BP CC
 
Chap3 3 12
Chap3 3 12Chap3 3 12
Chap3 3 12
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
SSDT unleashed
SSDT unleashedSSDT unleashed
SSDT unleashed
 
Building a Testable Data Access Layer
Building a Testable Data Access LayerBuilding a Testable Data Access Layer
Building a Testable Data Access Layer
 
Ado
AdoAdo
Ado
 
Testing 101
Testing 101Testing 101
Testing 101
 
JDBC Connectivity Model
JDBC Connectivity ModelJDBC Connectivity Model
JDBC Connectivity Model
 
Writing better tests for your java script app
Writing better tests for your java script appWriting better tests for your java script app
Writing better tests for your java script app
 
SELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdfSELJE_Database_Unit_Testing_Slides.pdf
SELJE_Database_Unit_Testing_Slides.pdf
 
java.pptx
java.pptxjava.pptx
java.pptx
 
Apache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI ToolboxApache DeltaSpike: The CDI Toolbox
Apache DeltaSpike: The CDI Toolbox
 
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolboxApache DeltaSpike the CDI toolbox
Apache DeltaSpike the CDI toolbox
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Test studiowebinaraugcodedstep
Test studiowebinaraugcodedstepTest studiowebinaraugcodedstep
Test studiowebinaraugcodedstep
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
 

Recently uploaded

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 

Recently uploaded (20)

Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 

In Memory Unit Testing with Apache DbUnit

  • 1. In-Memory Unit Tests with Apache DbUnit & HSQL DB Presented By Sabir Khan
  • 2. Agenda  In Memory Unit Testing - Need  In Memory Unit Testing - Architecture  In Memory Unit Testing – Tools Needed  In Memory Unit Testing – Steps  In Memory Unit Testing – Code Samples  In Memory Unit Testing – Challenges  Thanks
  • 3. In Memory Unit Testing - Need • Unit Tests might be required to run at following stages – during code development, code integration, build creation and might be at deployment time too. • During Development – Tests have to be very fast – should take less than 5 seconds due to frequent runs of tests and that frequent code changes didn’t break anything else • As far as unit testing is concerned, setting up connection with actual DB and running actual queries etc. is very slow • In-Memory testing is better than no testing at all – since we generally mock db connection objects etc. and don’t write unit tests for DAO Layer at all while generally there is too much code and logic at DAO layer too • During deployments – unit tests are run before starting of the application or other system components so DB might not be available or we don’t expect DB to be available for unit test runs
  • 4. In Memory Unit Testing – Need…Contd.. • If unit tests fail due to DB not being available – it would still be counted as a failure and deployment might not proceed • Tests can be run on systems that don’t have connectivity to real databases which is generally the case for build boxes • Tests are run on consistent data because data resides in checked in xml files. With actual DB, we will have to prepare data on all developer systems. • Parallel Test Execution – Each test can have its own In – memory database so tests can be run in parallel as far as data is concerned. DB locking and other contentious issues will not occur • With Maven, it has become easy to run unit tests and there are projects where successful run of unit tests during deployments is a Go – No GO factor for production deployments – if unit tests fail, deployment is a No GO
  • 5. In Memory Unit Testing – Need…Contd.. • Using actual DB for unit tests might corrupt the test data because that is usually meant for integration tests • Code Coverage – If organization mandates a certain percentage of code coverage for unit tests, DAO code can’t be left without unit tests as it might not be possible to achieve desired coverage leaving DAO layer code. Mocking Connection etc. results in very fake kind of unit tests with no value and there is no use of achieving code coverage just for the sake of formality
  • 6. In-Memory Unit Testing - Architecture
  • 7. In-Memory Unit Testing – Tools Needed  First, you need a database which supports In – Memory mode i.e. full db gets loaded in memory, tables & data are created in memory and all these run time structures vanish once tests finish. Nothing persists on disk. H2 , HSQL and MySQL databases support in-memory mode. I used HSQLDB for my project and this presentation  Secondly, You need an API to Connect to In-Memory database, table creation , preparing and loading of data. I used Apache DBUnit for this - dbunit-2.4.9.jar  Then you need a Unit Testing Framework like JUnit etc.  So you will write unit tests in JUnit, connecting to in – memory database ( which is equivalent to your real RDBMS ) for your data needs
  • 8. In-Memory Unit Testing – Steps  Include HSQL DB Jar to your project in any way suitable to you  Use below values for connection string, private static final String JDBC_DRIVER = org.hsqldb.jdbcDriver.class.getName(); private static final String JDBC_URL ="jdbc:hsqldb:mem:tests"; private static final String USER = "sa"; private static final String PASSWORD = ""; User and Password are fixed and notice URL’s :mem: portion which indicates in – memory mode. Include Apache DbUnit and JUnit dependencies to your project
  • 9. In-Memory Unit Testing – Code Samples…Java As illustrated in code sample, we create DB connection & db tables at @BeforeClass time and set up data at @Before time. Public class TestClass{ private static final String JDBC_DRIVER = org.hsqldb.jdbcDriver.class.getName(); private static final String JDBC_URL ="jdbc:hsqldb:mem:tests"; private static final String USER = "sa"; private static final String PASSWORD = ""; private static IDatabaseTester databaseTester; private IDataSet dataSet1,dataSet2; @BeforeClass public static void inMemDBSetUp() throws Exception{ databaseTester=new JdbcDatabaseTester(JDBC_DRIVER,JDBC_URL,USER,PASSWORD); Connection connection=databaseTester.getConnection().getConnection(); createTables(connection); } @AfterClass public static void inMemDbCleanUp(){} …….contd…
  • 10. In-Memory Unit Testing – Code Samples…Java..Contd @Before public void testDataSetUp() throws Exception{ service=new Service() ; //assume this is your service class to be tested service.setDBConnection(databaseTester.getConnection().getConnection()); dataSet1=readDataSet1(); cleanlyInsert(dataSet1); dataSet2=readDataSet2(); etc cleanlyInsert(dataSet2); }
  • 11. In-Memory Unit Testing – Code Samples…Java..Contd private static void createTables(Connection connection){ //Here we use connection object to create tables, table constraints etc like in real DB //This will be very similar to plain jdbc code where your prepare statements from SQLS and execute those statements } //This method will read data table data kept in XML file and will pass on to cleanlyInsert method private IDataSet readDataSet1() throws Exception { return new FlatXmlDataSetBuilder().build(TestClass.class.getResourceAsStream("/data.xml")); } //similarly readDataSet2() method etc //this method will load data into tables private void cleanlyInsert(IDataSet dataSet) throws Exception { databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT); databaseTester.setDataSet(dataSet); databaseTester.onSetup(); } }//end testclass
  • 12. In-Memory Unit Testing – Code Samples…XML data  Data read in Java class resides in XML files in below format, data.xml <?xml version="1.0" encoding="UTF-8"?> <dataset> <TABLE_NAME COLUMN_1=VALUE1, COLUMN2=VALUE2 …/> </dataset> Each row in above xml represents a single row in mentioned table at start of tag. Similarly, a second row can be added for another table and so on…
  • 13. In-Memory Unit Testing – Challenges  First challenge that I faced is the syntax differences between actual database system and HSQLDB so there might be quite a bit of effort required for creation of DDL queries like CREATE TABLE statement etc.  Schema Definition: I found it very hard to include schema name in data xml. I didn’t found a way out for that.

Editor's Notes

  1. NOTE: To change the image on this slide, select the picture and delete it. Then click the Pictures icon in the placeholder to insert your own image.