springjunitstruts2struts2-junit-plugin

No qualifying bean of type for a bean in the Action I'm testing


I work on a project on eclipse, using tomcat, maven, spring, hibernate and struts. We've got 2 apps: core that contains all the beans (services) and web with the actions views etc.

I made the JUnit tests for the services and decided to try doing some tests for the Actions. Here is an example of what I'm trying to do:

Action

@Action(value = "/modif/register")
@ResultPath("...")
public class A{
    @Autowired
    private ExampleService exampleService;

    public String execute(){
        Example = exampleService.find(...);
        ...
        ...
    }
}

Test

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class ATest extends StrutsSpringTestCase {

    @Before
    public void setUp(){
        try {
            super.setUp();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testExecute() throws Exception{
        request.setParameter(...);
        //filling up the request

        ActionProxy proxy = super.getActionProxy("/modif/register");
        A register =    (A) proxy.getAction();
        String result = proxy.execute();
    }

}

Config

@Configuration
@ComponentScan(basePackages = {"web","core"} )
public class Config {
  //configuration
}

Each time i try to launch this test, I've got this error on the line ActionProxy proxy = super.getActionProxy("/modif/register");

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'web.action.A': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public core.service.ExampleService web.action.A.exampleService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [core.service.ExampleService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I got this error not matter wich bean I call. They all work in the core app and in my Action, i can even call them directly in my test without any error but it fails each time I try to launch a test.

Does anyone knows what could possibly throw this exception?


Solution

  • The BeanCreationException is thrown because there is no ExampleService bean in your test context. It can happen because the right context isn't loaded for your action's test.

    Since you are using JUnit 4, instead of StrutsSpringTestCase you should extend the StrutsSpringJUnit4TestCase class which will play nicer with @RunWith(SpringJUnit4ClassRunner.class) and context loading.