lundi 23 mars 2015

Should I use a seperate beans.xml configuration for instantiating objects in my unit tests?

Here's my Beans.xml for my application



<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/QEDs1e">


<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>


It's one Room bean that has a BottleCounter bean as a property.


Now, I want to write a 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't directly reference myBottleCounter as it's a inner bean? And gives me No bean named 'myBottleCounter' is defined.


So should instead, I be defining my test beans in a seperate xml?


eg.


testBeans.xml



<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://ift.tt/GArMu6"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/QEDs1e">


<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));
}

}

Aucun commentaire:

Enregistrer un commentaire