001/* 002 * ModeShape (http://www.modeshape.org) 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.modeshape.common.naming; 017 018import static org.hamcrest.core.Is.is; 019import static org.hamcrest.core.IsSame.sameInstance; 020import static org.junit.Assert.assertThat; 021import javax.naming.InitialContext; 022import javax.naming.NameNotFoundException; 023import junit.framework.AssertionFailedError; 024import org.junit.After; 025import org.junit.Before; 026import org.junit.Test; 027 028/** 029 * @author Randall Hauch 030 */ 031public class SingletonInitialContextTest { 032 033 private String validName; 034 private Object registeredObject; 035 036 @Before 037 public void beforeEach() { 038 this.validName = "java:jboss/unit/test/name"; 039 this.registeredObject = "This is the registered object"; 040 } 041 042 @After 043 public void afterEach() { 044 SingletonInitialContextFactory.tearDown(); 045 } 046 047 @Test 048 public void shouldCreateInitialContextAndRegisterAnObject() throws Exception { 049 SingletonInitialContext.register(this.validName, this.registeredObject); 050 for (int i = 0; i != 10; ++i) { 051 assertThat(new InitialContext().lookup(this.validName), is(sameInstance(this.registeredObject))); 052 } 053 } 054 055 @Test 056 public void shouldTearDownMockInitialContextUponRequest() throws Exception { 057 // Set it up ... 058 // (Don't want to use 'expected', since the NamingException could be thrown here and we wouldn't know the difference) 059 SingletonInitialContext.register(this.validName, this.registeredObject); 060 for (int i = 0; i != 10; ++i) { 061 assertThat(new InitialContext().lookup(this.validName), is(sameInstance(this.registeredObject))); 062 } 063 // Tear it down ... 064 SingletonInitialContextFactory.tearDown(); 065 try { 066 new InitialContext().lookup(this.validName); 067 throw new AssertionFailedError("Failed to throw exception"); 068 } catch (NameNotFoundException e) { 069 // expected 070 } 071 } 072 073}