Testdata generation
September 26th, 2011We’ve all being there, we’ve all had this on a project once or maybe even more times. The assignment is to build an application, but there is no data for you to work with. There could be any number of reasons this could be the case to name a few, the web-service that should be connected is not done in time, the database migration is postponed. Then someone has to create database scripts with test data, or implement a test web-services. This is all a waste of time.
But lucky for you now there is a solution.
I’ve created an little test data framework that is easy to setup and will create test data automatically. So how does it work? Simple, its entry point is a method interceptor that you can wrap around anything you want, it doesn’t even have to be an implementation. So that DAO you want to use, but the database is still empty, just let the framework step into place and all the methods return the data that you want.
It can also be handy to create test data for you unit test. You need to test if you bean serialization works, or want to put an entity into a in memory database with dbunit. Just call the framework with you bean class and the framework will return an instance filled with test data. It will read the existing annotations that you have on your entity bean an will only generate data that is valid for you bean.
Here is an example of how it works:
//Create an instance of the Employee class and fill it with test data.
Employee employee = TestData.createBeanInstance(Employee.class);
//Annotations that restrict the data for first name are recognized.
assertNotNull(employee.getFirstName());
To create a service that returns test data on it’s service methods:
//create a instance of the service class/interface that will return test data
Service exampleService = TestData.createService(Service.class);
//this now returns a list of employee instances that are filled with test data
List<Employee> employees = exampleService.findByName("name");
Create a dbunit xml file:
//create a file
File fileLocation = File.createTempFile("file", ".xml");
//populate the file with test data for the employee
TestData.createDBUnitDataSet(Employee.class, fileLocation);
If employee has relations with other classes, like employees have managers these objects will also be in the generated xml file.
To give it a spin add the following into you pom.xml
<dependency>
<groupId>ch.nerdin</groupId>
<artifactId>testdata-framework</artifactId>
<version>0.10</version>
</dependency>
or if you use ivy, gradle or something else you properly know how to use this information as well.
So nothing holding you back to make your data driven test easier to setup, or to stub out you migration points. I’m hosting this code on github so if you have issues, comments or even better contribute please do so.
Posted by Erik Jan