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.util;
017
018import static org.junit.Assert.assertNotNull;
019import org.junit.Test;
020import java.net.URL;
021import java.net.URLClassLoader;
022import java.util.Arrays;
023import java.util.Collections;
024
025/**
026 * Unit test for {@link DelegatingClassLoader}
027 *
028 * @author Horia Chiorean
029 */
030public class DelegatingClassLoaderTest {
031
032    private static final URLClassLoader EMPTY_URL_CLASS_LOADER = new URLClassLoader(new URL[0], null);
033
034    @Test(expected = IllegalArgumentException.class )
035    public void shouldNotAllowNullDelegates() throws Exception {
036        new DelegatingClassLoader(null, null);
037    }
038
039    @Test
040    public void shouldAllowNullParent() throws Exception {
041        new DelegatingClassLoader(null, Collections.<ClassLoader>emptyList());
042    }
043
044    @Test(expected = ClassNotFoundException.class)
045    public void shouldNotClassIfNoDelegateCanFindIt() throws Exception {
046        DelegatingClassLoader classLoader = new DelegatingClassLoader(null, Arrays.asList(EMPTY_URL_CLASS_LOADER));
047        classLoader.loadClass(DelegatingClassLoaderTest.class.getName());
048    }
049
050    @Test
051    public void shouldFindClassIfOneDelegateCanFindIt() throws Exception {
052        DelegatingClassLoader classLoader = new DelegatingClassLoader(null, Arrays.asList(EMPTY_URL_CLASS_LOADER,
053                                                                                          DelegatingClassLoaderTest.class.getClassLoader()));
054        assertNotNull(classLoader.loadClass(DelegatingClassLoaderTest.class.getName()));
055    }
056
057    @Test
058    public void shouldFindClassIfParentCanFindIt() throws Exception {
059        DelegatingClassLoader classLoader = new DelegatingClassLoader(DelegatingClassLoaderTest.class.getClassLoader(),
060                                                                      Arrays.asList(EMPTY_URL_CLASS_LOADER));
061        assertNotNull(classLoader.loadClass(DelegatingClassLoaderTest.class.getName()));
062    }
063}