如何使用Spring Autowire编写JUnit测试?

以下是我使用的文件:

component.xml文件

    

ServiceImpl.java

 @org.springframework.stereotype.Service public class ServiceImpl implements MyService { @Autowired private MyDAO myDAO; public void getData() {...} } 

ServiceImplTest.java

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath*:conf/components.xml") public class ServiceImplTest{ @Test public void testMyFunction() {...} } 

错误:

 16:22:48.753 [main] ERROR ostest.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@2092dcdb] to prepare test instance [services.ServiceImplTest@9e1be92] org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'services.ServiceImplTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private services.ServiceImpl services.ServiceImplTest.publishedServiceImpl; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [services.ServiceImpl] 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)} at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287) ~[spring-beans.jar:3.1.2.RELEASE] 

确保您已导入正确的包。 如果我记得正确,有两个不同的自动assembly包。 应该是: org.springframework.beans.factory.annotation.Autowired;

这看起来对我来说很奇怪:

 @ContextConfiguration("classpath*:conf/components.xml") 

这是一个适合我的例子:

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "/applicationContext_mock.xml" }) public class OwnerIntegrationTest { @Autowired OwnerService ownerService; @Before public void setup() { ownerService.cleanList(); } @Test public void testOwners() { Owner owner = new Owner("Bengt", "Karlsson", "Ankavägen 3"); owner = ownerService.createOwner(owner); assertEquals("Check firstName : ", "Bengt", owner.getFirstName()); assertTrue("Check that Id exist: ", owner.getId() > 0); owner.setLastName("Larsson"); ownerService.updateOwner(owner); owner = ownerService.getOwner(owner.getId()); assertEquals("Name is changed", "Larsson", owner.getLastName()); } 

我认为代码库中的某个地方是@Autowiring具体的类ServiceImpl ,你应该自动assembly它的接口(可能是MyService )。