Pregunta

I have one irritating problem right now. My tests fail due to an autowire.

Could not autowire field: private k.dao.CompanyDao k.dao.CompanyDaoTest.companyDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [k.dao.CompanyDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

I think @ContextConfiguration can be the problem?

The test

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:**/servlet-context.xml", "classpath:**/root-context.xml", "classpath:**/ccc-jpa.xml" })
public final class CompanyDaoTest {

    @Autowired
    private CompanyDao companyDao;

    @Test
    public void testTest() {

    }
}

CompanyDao

public interface CompanyDao extends GenericDao<Company> {

}

CompanyDaoJpa

@Repository("companyDao")
public class CompanyDaoJpa extends GenericDaoJpa<Company> implements CompanyDao {

    public CompanyDaoJpa() {
        super(Company.class);
    }
}

GenericDao

public interface GenericDao<T extends DomainObject> {

    public T get(Long id);

    public List<T> getAll();

    public T save(T object);

    public T delete(T object);

}

servlet-context.xml

    <annotation-driven />

    <context:component-scan base-package="k"/>
¿Fue útil?

Solución

I guess your test doesn't load servlet-context.xml at all.

You reference servlet-context.xml as a classpath resource, but servlet-context.xml is usually located under WEB-INF, which is not a part of application classpath. Note that Spring doesn't complain about missing config files when they are referenced with wildcards ( classpath:**/servlet-context.xml), so that your test starts silently even if config files cannot be found.

There are no good ways to access Spring xml files located in WEB-INF from unit tests. If you want to run tests against them, you need to move them to the classpath (i.e. to something like src or resources, depending on your project layout). Since DispatcherServlet and ContextLoaderListener expect to find these files under WEB-INF, you also need to reconfigure them using their respective contextConfigLocation parameters. For example, in the case of DispatcherServlet:

<init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:**/servlet-config.xml</param-value>
</init-param>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top