Here is my Beans.xml for my application
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="myRoom" class="org.world.hello.Room">
<property name="bottleCounter">
<bean id="myBottleCounter" class="org.world.hello.BottleCounter" />
</property>
<property name="numBottles" value="10"></property>
</bean>
</beans>
This is one Roombean that has a BottleCounterbean property as a property.
Now I want to write unit testing for BottleCounter.
public class BottleCounterTest {
ApplicationContext context;
@Before
public void setUp()
{
context = new ClassPathXmlApplicationContext("Beans.xml");
}
@Test
public void testOneBottle() {
BottleCounter bottleCounter = (BottleCounter) context.getBean("myBottleCounter");
assertEquals("1 bottles of beer on the wall1 bottles of beer!", bottleCounter.countBottle(1));
}
}
But I can not directly refer to myBottleCounterhow the internal bean? And gives me No bean named 'myBottleCounter' is defined.
So, instead, I define my beans test in a separate xml?
eg.
testBeans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="testRoom" class="org.world.hello.Room">
<property name="bottleCounter">
<bean id="myBottleCounter" class="org.world.hello.BottleCounter" />
</property>
<property name="numBottles" value="3"></property>
</bean>
<bean id="testBottleCounter" class="org.world.hello.BottleCounter" />
</beans>
BottleCounterTest.java
public class BottleCounterTest {
ApplicationContext context;
@Before
public void setUp()
{
context = new ClassPathXmlApplicationContext("testBeans.xml");
}
@Test
public void testOneBottle() {
BottleCounter bottleCounter = (BottleCounter) context.getBean("testBottleCounter");
assertEquals("1 bottles of beer on the wall1 bottles of beer!", bottleCounter.countBottle(1));
}
}
source
share