Reputation: 8240
I am trying to learn how to use applicationContext. My goal is to swap out a mock data repository for a real one when using my unit tests. I don't want to do this explicitly, I want to do this with dependency injection.
So as a simple test before I make things complicated, I'm simply trying to get a bean out of my applicationContext.xml. From what I've read, this should work:
@ContextConfiguration(locations = "/applicationContext.xml")
public class ResultsListTests {
@Resource
CompanyResult resultBean;
@Test
public void shouldAddResults() {
assertEquals(resultBean.getCompanyName(), "Microsoft");
But my resultBean is always null. Here is my applicationContext.xml, which is located under WebContent/WEB-INF:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="resultBean" name="resultBean" class="com.trgr.cobalt.company.domain.CompanyResult">
<property name="companyName">
<value>Microsoft</value>
</property>
</bean>
</beans>
So why is my resultBean always null? What have I done incorrectly?
Upvotes: 0
Views: 2038
Reputation: 9150
You are missing a @RunWith(SpringJUnit4ClassRunner.class)
annotation:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/applicationContext.xml")
public class ResultsListTests {
@Resource
CompanyResult resultBean;
@Test
public void shouldAddResults() {
assertEquals(resultBean.getCompanyName(), "Microsoft");
}
}
BTW, in your sample, WebContent/WEB-INF
is not the proper location for applicationContext.xml
.
If you specify @ContextConfiguration(locations = "/applicationContext.xml")
then Spring will look for applicationContext.xml
at the root of the classpath, not in WebContent/WEB-INF
(jUnit is 100% unaware of the fact that this is a web application).
For more information, see Spring reference documentation.
Upvotes: 1