我正在尝试为 Alfresco SDK 应用创建测试环境。我需要测试由我创建的服务,该服务具有 ServiceRegistry 作为属性,由Spring通过构造函数注入。如果应用程序正在运行,该服务运行良好。
对于bean声明,我使用注释:
@Service(value = "customFormService")
public class CustomFormService implements FormService<String> {
private final ServiceRegistry serviceRegistry;
@Autowired
public CustomFormService(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
在服务应用程序上下文中:
/amp/config/module/sampleapp/context/service-context.xml
我声明<context:component-scan base-package="com.base"/>
启用带注释的组件扫描
问题是当我尝试创建这样的单元测试时:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations = {"classpath*:config/alfresco/module/sampleapp/context/service-context.xml"}
)
public class DocumentManagementTest {
@Autowired
@Qualifier(value = "customFormService")
FormService<String> customFormService;
@Test
public void testWiring() {
Assert.assertNotNull(customFormService);
}
}
我得到一个例外:
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.base.form.service.FormService] 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), @org.springframework.beans.factory.annotation.Qualifier(value=customFormService}
当应用程序运行时,注入工作正常并且在Junit测试用例中失败,这非常令人困惑。
答案 0 :(得分:1)
如果您想在课程中注入 ServiceRegistry ,则需要添加属性
<bean id="reject-content" class="com.repo.RejectContent"
parent="action-executer">
<property name="serviceRegistry">
<ref bean="ServiceRegistry" />
</property>
</bean>
像你上面的bean一样。
com.repo.RejectContent
在RejectContent类中,您需要为服务注册表创建setter,如下所示:
private ServiceRegistry serviceRegistry;
public void setServiceRegistry(ServiceRegistry serviceRegistry) {
this.serviceRegistry = serviceRegistry;
}
之后,您可以使用 serviceRegistry 。
答案 1 :(得分:0)
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
...
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[] { "classpath:alfresco/application-context.xml" });
ServiceRegistry serviceRegistry = (ServiceRegistry) applicationContext.getBean(ServiceRegistry.SERVICE_REGISTRY);
...