JNDI Resource with Spring Junit

在Web Application中,我們免不了會需要用到JNDI的功能,

這在正常的runtime沒有問題,但要是當我們需要在Junit測試時使用到JNDI就會出問題了.

因為Junit runtime環境下並沒有container來提供JNDI的機制.

Senario:

container: Jboss 7

jndi bean: ManagedExecutorService (Exposed Interface: ExecutorService) -> 網路上大多數的問題是在探討 jndi 用在 datasource 上的用法

framework: Spring 4

Spring jndi configuration:

<!-- look up for the ee executor service -->
<jee:jndi-lookup id="defaultManagedExecutorService"
     jndi-name="java:jboss/ee/concurrency/executor/default" />

Solution:

解法很簡單,只要使用 Spring 的 SimpleNamingContextBuilder 就可以解決,這個class就是為了test environment而生,他會模擬 container 建立 jndi context 的機制建出 name context ,之後就可以依照需求註冊所需之bean/class.

 

@BeforeClass
public static void setUpClass() throws Exception {
   SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
   ExecutorService es = Executors.newFixedThreadPool(5);
   builder.bind("java:jboss/ee/concurrency/executor/default", es);
   builder.activate();
}

Ref:

  1. http://stackoverflow.com/questions/5682732/how-does-an-application-that-uses-springs-simplenamingcontextbuilder-know-to-se
  2. http://stackoverflow.com/questions/19976745/how-to-run-junit-test-in-spring-injecting-jboss-jndi-datasources
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s