I am using Unitils with Spring for unit testing. I've configured Spring with datasource using a properties file.
My question is how can I use the same datasource or the same properties for Unitils?
Unitils expects a file in the classpath unitils.properties with database configuration parameters like url, user, password and driver.
I've tried to configure Unitils using the properties used in the Spring configuration as below but it is not working.
database.driverClassName=${jdbc.driver.class}
Thanks, Adi
Ryan answer is correct and helpful as well though I've used different approach.
I extended the class
PropertiesDataSourceFactory
ro override the methods as follows:and also wrote a SystemPropertiesReader as:
and added a bean with the properties file:
add the following to unitils.properties:
Just want to add some idea and im not sure if it is a best practice or not so correct me if theres something wrong.
-src
--TestPackage
---BaseServiceTest.class
---BlogspotServiceTest.class
--hibernate.cfg.xml
-web
--WEB-INF
---blogspot-servlet-test.xml
---jdbc-test.properties
in my case I used my blogspot-servlet-test.xml to call or to create the datasource
MY jdbc-test.properties file
For hibernate.cfg.xml
and i created BaseClass for me to lessen creating of multiple @SpringApplicationContext annotation and it is also use to configure common configuration needed in testing other class, just extends it.
i used @SpringApplicationContext to load the datasource and other bean configurations on my BaseClass and this is how i implement it.
Below : see Spring-Unitils Tutorial for more details
NOTE: please create unitils.properties and unitils-local.properties inside TestPackage to be able to run the program.
For @SpringBean explanation and other annotation please read :
Unitils-EasyMock
One potential solution... You could have your Spring configuration read its datasource parameters from the unitils.properties, instead of the other way around. Probably not ideal.
I believe unitils is using spring under the covers, so you might also try adding your datasource context in your unitils tests by using
@SpringApplicationContext
. If you could figure out the name of the datasource bean setup by unitils when it starts up, you could override it in your context (assuming the unitils datasource bean is created before the other spring beans are which may/may not be true.)e.g.
@SpringApplicationContext({"correctDataSourceContext.xml"})
EDIT: Another option that will definitely work: https://stackoverflow.com/a/6561782/411229 Basically instantiate Unitils yourself and set the properties manually.