Friday, November 21, 2008

[Spring 2.5] context:component-scan does not with @autowired in JUnit test.

A problem exists in Spring 2.5.1 (Maybe also later versions up until 2.5.4?) that cause context:component-scan not to detect the classes you wish to inject in your test classes. Instead you have to add a bean tag defining the bean that you wish to inject in your JUnit test case.

Example

applicationContext.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"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
 <context:component-scan base-package="com.maaloe.spring" />
 <context:annotation-config/>
</beans>

TestCase:
package com.maaloe.spring;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import dk.telia.cas.command.CommandException;
import dk.telia.cas.dataobject.CPRInfo;
import dk.telia.cas2.test.AbstractSpringTest;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:applicationContext.xml"})
public class MyServiceTest {

    @Autowired
    private MyTestService myTestService;

    @SuppressWarnings("unchecked")
    @Test
    public void test() {
        System.out.println("Test service class: " + myTestService.myToString());
    }
}

Service interface:
package com.maaloe.spring;

public interface MyTestService {
    String myToString();
}

Service Implementation:
package com.maaloe.spring;

import org.springframework.stereotype.Component;

@Component
public class MyTestServiceImpl implements MyTestService {
    public String myToString() {
        return "Ping...";
    }
}

The above does not work until you add:

<bean id="myTestService" class="com.maaloe.spring.MyTestServiceImpl"/>


to your applicationContext.xml file if you are running Spring 2.5.1.

Anyways... Simply fix it by upgrading Spring to 2.5.4.

Enjoy!

No comments: