001 /*****************************************************************************
002 * Copyright (C) PicoContainer Organization. All rights reserved. *
003 * ------------------------------------------------------------------------- *
004 * The software in this package is published under the terms of the BSD *
005 * style license a copy of which has been included with this distribution in *
006 * the LICENSE.txt file. *
007 * *
008 * Original code by *
009 *****************************************************************************/
010 package org.picocontainer.defaults;
011
012 import org.picocontainer.parameters.ComponentParameter;
013 import org.picocontainer.testmodel.DecoratedTouchable;
014 import org.picocontainer.testmodel.DependsOnTouchable;
015 import org.picocontainer.testmodel.SimpleTouchable;
016 import org.picocontainer.testmodel.Touchable;
017 import org.picocontainer.DefaultPicoContainer;
018
019 import junit.framework.TestCase;
020
021 /**
022 * @author Thomas Heller
023 * @author Aslak Hellesøy
024 */
025 public class ComponentKeysTestCase extends TestCase {
026 public void testComponensRegisteredWithClassKeyTakePrecedenceOverOthersWhenThereAreMultipleImplementations() throws Exception {
027 DefaultPicoContainer pico = new DefaultPicoContainer();
028 pico.addComponent("default", SimpleTouchable.class);
029
030 /**
031 * By using a class as key, this should take precedence over the other Touchable
032 */
033 pico.addComponent(Touchable.class, DecoratedTouchable.class, new ComponentParameter("default"));
034
035 Touchable touchable = pico.getComponent(Touchable.class);
036 assertEquals(DecoratedTouchable.class, touchable.getClass());
037 }
038
039 public void testComponentAdapterResolutionIsFirstLookedForByClassKeyToTheTopOfTheContainerHierarchy() {
040 DefaultPicoContainer pico = new DefaultPicoContainer();
041 pico.addComponent("default", SimpleTouchable.class);
042
043 // Use the List variant instead, so we get better test coverage.
044 pico.addComponent(Touchable.class, DecoratedTouchable.class, new ComponentParameter("default"));
045
046 DefaultPicoContainer grandChild = new DefaultPicoContainer(new DefaultPicoContainer(new DefaultPicoContainer(pico)));
047
048 Touchable touchable = grandChild.getComponent(Touchable.class);
049 assertEquals(DecoratedTouchable.class, touchable.getClass());
050
051 }
052
053 public void testComponentKeysFromParentCannotConfuseTheChild() throws Exception {
054 DefaultPicoContainer pico = new DefaultPicoContainer();
055 pico.addComponent("test", SimpleTouchable.class);
056
057 DefaultPicoContainer child = new DefaultPicoContainer(pico);
058
059 child.addComponent("test", DependsOnTouchable.class);
060
061 DependsOnTouchable dot = (DependsOnTouchable) child.getComponent("test");
062
063 assertNotNull(dot);
064 }
065
066 }