2 * Copyright 2005-2010 the original author or authors.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package org.wamblee.test.jndi;
18 import java.util.Hashtable;
20 import javax.naming.Context;
21 import javax.naming.NamingException;
22 import javax.naming.spi.InitialContextFactory;
25 * Test initial context factory used for testing software in a Java SE
26 * environnment that uses JNDI to retrieve objects.
28 * See {@link #bind(String, Object)} to resp. register the initial context.
30 * To start mocking the JNDI tree, call {@link #register()}.
32 * To bind objects in the JNDI tree simply use the standard JNDI api:
35 * InitialContext context = new InitialContext();
36 * MyClass myObj = ...;
37 * context.bind("a/b", myObj);
40 * When finished with a test case, call {@link #unregister()} to unregister the
43 public class StubInitialContextFactory implements InitialContextFactory {
45 private static Context CONTEXT;
47 private static void initialize() {
49 CONTEXT = new StubInitialContext();
50 } catch (NamingException e) { // can't happen.
51 throw new RuntimeException(e);
56 * This method must be called to register this initial context factory as
57 * the default implementation for JNDI.
61 public static void register() {
62 // sets up the InitialContextFactoryForTest as default factory.
63 System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
64 StubInitialContextFactory.class.getName());
65 if (CONTEXT == null) {
71 * Unregisters the initial context factory
73 public static void unregister() {
74 System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "");
78 public Context getInitialContext(Hashtable<?, ?> aEnvironment)
79 throws NamingException {