01: /*
02: * Copyright 2002-2005 the original author or authors.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
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.
15: */
16:
17: package org.springframework.mock.jndi;
18:
19: import java.util.Collections;
20: import java.util.HashMap;
21: import java.util.Map;
22:
23: import javax.naming.NamingException;
24:
25: import org.springframework.jndi.JndiTemplate;
26:
27: /**
28: * Simple implementation of JndiTemplate interface that always returns
29: * a given object. Very useful for testing. Effectively a mock object.
30: *
31: * @author Rod Johnson
32: * @author Juergen Hoeller
33: */
34: public class ExpectedLookupTemplate extends JndiTemplate {
35:
36: private final Map jndiObjects = Collections
37: .synchronizedMap(new HashMap());
38:
39: /**
40: * Construct a new JndiTemplate that will always return given objects
41: * for given names. To be populated through <code>addObject</code> calls.
42: * @see #addObject(String, Object)
43: */
44: public ExpectedLookupTemplate() {
45: }
46:
47: /**
48: * Construct a new JndiTemplate that will always return the
49: * given object, but honour only requests for the given name.
50: * @param name the name the client is expected to look up
51: * @param object the object that will be returned
52: */
53: public ExpectedLookupTemplate(String name, Object object) {
54: addObject(name, object);
55: }
56:
57: /**
58: * Add the given object to the list of JNDI objects that this
59: * template will expose.
60: * @param name the name the client is expected to look up
61: * @param object the object that will be returned
62: */
63: public void addObject(String name, Object object) {
64: this .jndiObjects.put(name, object);
65: }
66:
67: /**
68: * If the name is the expected name specified in the constructor,
69: * return the object provided in the constructor. If the name is
70: * unexpected, a respective NamingException gets thrown.
71: */
72: public Object lookup(String name) throws NamingException {
73: Object object = this .jndiObjects.get(name);
74: if (object == null) {
75: throw new NamingException("Unexpected JNDI name '" + name
76: + "': expecting " + this.jndiObjects.keySet());
77: }
78: return object;
79: }
80:
81: }
|