【发布时间】:2015-03-24 03:33:05
【问题描述】:
这是我的应用程序的 Beans.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="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>
这是一个Room bean,它具有BottleCounter bean 作为属性。
现在,我想为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));
}
}
但是我不能直接引用myBottleCounter,因为它是一个内部bean?并给我No bean named 'myBottleCounter' is defined。
那么,我应该在单独的 xml 中定义我的测试 bean 吗?
例如。
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));
}
}
【问题讨论】:
标签: spring unit-testing instantiation