/*
 * Copyright 2002-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package test.feature.misc;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import org.springframework.config.java.annotation.Bean;
import org.springframework.config.java.annotation.Configuration;
import org.springframework.config.java.context.JavaConfigApplicationContext;

import test.common.beans.TestBean;


/**
 * Integration tests for creating context hierarchies using
 * {@link JavaConfigApplicationContext}.
 *
 * @see     test.feature.xmlbootstrap.JavaAndXmlContextHierarchyTests.JavaAndXmlContextHierarchyTests
 * @author  Chris Beams
 */
public class ContextHierarchyTests {

    @Test
    public void testHierarchicalContexts() {
        JavaConfigApplicationContext c = new JavaConfigApplicationContext();
        c.addConfigClass(Child.class);
        JavaConfigApplicationContext p = new JavaConfigApplicationContext(Parent.class);
        c.setParent(p);
        c.refresh();
        assertEquals("alice", c.getBean(TestBean.class, "child").getName());
        assertEquals("mother", p.getBean(TestBean.class, "parent").getName());
        assertEquals("mother", c.getBean(TestBean.class, "parent").getName());
    }

    @Test
    public void testHierarchicalContexts2() {
        final JavaConfigApplicationContext p = new JavaConfigApplicationContext(Parent.class);
        assertEquals("mother", p.getBean(TestBean.class, "parent").getName());

        JavaConfigApplicationContext c = new JavaConfigApplicationContext();
        c.addConfigClass(Child.class);
        c.setParent(p);
        c.refresh();
        assertEquals("alice", c.getBean(TestBean.class, "child").getName());
        assertEquals("mother", ((TestBean) c.getParent().getBean("parent")).getName());
        assertEquals("mother", ((TestBean) c.getBean("parent")).getName());
    }

    @Configuration
    static class Child {
        @Bean
        public TestBean child() { return new TestBean("alice"); }
    }

    @Configuration
    static class Parent {
        @Bean
        public TestBean parent() { return new TestBean("mother"); }
    }

}
