How can I lookup Jndi name in junit test class? I do not want to use separate configration file for junit and not giving datasource properties? I specifically need to do jndi lookup in my test class.
3 Answers
Here is a quote from the official Spring docs http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/testing.html#mock-objects-jndi:
The org.springframework.mock.jndi package contains an implementation of the JNDI SPI, which you can use to set up a simple JNDI environment for test suites or stand-alone applications.
From this doc I use Spring context configuration class which declares a datasource:
@Configuration
public class JndiDataConfig {
@Bean
public DataSource dataSource() throws Exception {
Context ctx = new InitialContext();
return (DataSource) ctx.lookup("java:comp/env/jdbc/datasource");
}
}

- 549
- 1
- 7
- 18
If you are using JBoss you should use minicontainer. It boot stap your application server from main (as J2SE application). AFAIK, there is no "standard" solution for this issue.
Alternative approach can be establish dedicated server for JUnit testing only, configure your JNDI environment manually (you can, hopefully, figure out how to do it, using your application server) in J2SE environment and connect to remote server.

- 5,661
- 7
- 37
- 57
If you prefer to test your classes outside a special environment like an application container you can use Simple-JNDI. It creates the JNDI environment for you and binds values from property files to it. So you can emulate the environment of your application container in case you defined some configuration parameters as environment objects. Also it can initialize a DataSource or a connection pool for you and bind it to a JNDI Context, so your code under test can access them as usual. See http://github.com/h-thurow/Simple-JNDI for more information.

- 764
- 4
- 12