I am trying to set up some jUnit testing. Our database is connected by the server using JNDI. We have an xml describing the setup in root.xml. How do I set up jUnit to hook up to the database? I'd prefer to have it just read the the stuff off of root.xml, but I'm open to setting it up anyway that works.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
I think you should try to mock out the database. Use appropriate framework, for example Mockito, it creates mocks and have DI abilities.
You can add Tomcat lib via maven dependency using below, to get it working.
I have used Simple-JNDI for this purpose for years now. It gives you an in-memory implementation of a JNDI Service and allows you to populate the JNDI environment with objects defined in property files. There is also support for loading datasources or connection pools configured in a file.
To get a connection pool you have to create a file like this:
In your application you can access the pool via
You can find more about it at https://github.com/h-thurow/Simple-JNDI.
TomcatJNDI helps with that situation too. It can process Tomcat’s configuration files and creates the same JNDI environment as Tomcat does, but without starting a server. So you can run classes with dependencies on Tomcat’s JNDI environment in e. g. JUnit tests.
Then your classes can lookup the DataSource as when they would run in Tomcat.
More about TomcatJNDI can be found here: https://github.com/h-thurow/TomcatJNDI
I found that the best way to do it is to use something called Simple-Jndi.
I added this to the maven file:
You can download the the package here, the download contains an instruction manual. http://code.google.com/p/osjava/downloads/detail?name=simple-jndi-0.11.4.1.zip&can=2&q=
After adding to to your project you just have to add a couple of properties files, per the instructions.
However, after you add the dependency, I believe you can add your jndi resources programmatically instead of using properties files. You do something like this: (new InitialContext()).rebind("datasource",myDatasource);
Would you like to create datasource programmatically on Application Server? Referene :
If you already created on Sever,
I've found this Blog: https://blogs.oracle.com/randystuph/entry/injecting_jndi_datasources_for_junit
About H2 Datasource: http://www.h2database.com/javadoc/org/h2/jdbcx/JdbcConnectionPool.html
So for my Code:
Note: I had to add Tomcat Library and the jars inside the Tomcat's bin directory to get it working