引起:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为'myAppDao'的bean时出错:

时间:2017-09-05 06:37:03

标签: java spring junit

我有一个dao类,它依赖于另一个实用程序类AuditStore

package myapp;
@Repository
public class MyAppHibernateDao {

    @Autowired
    public void setAuditStore(AuditStore auditStore) {
        ConnectorLoggingHelper.setAuditStore(auditStore);
    }

}

AuditStore.java

package myapp;
@Resource
public class AuditStore {
    //too many dependencies in this class including db connection 
}

现在我想为dao类编写集成测试,它不包括'AuditStore'的功能。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:META-INF/spring-myapp-db-connector-test.xml")
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class, TransactionalTestExecutionListener.class})
public class MyAppHibernateDaoIntegrationTest {


    @Test
    public void test() {
        //test code here
    }
}

我的xml配置文件是

<!--spring-myapp-db-connector-test.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- enable autowiring -->

 <context:annotation-config/>

 <bean id="myAppDao" class="myapp.MyAppHibernateDao">

</beans>

我运行此操作时遇到以下错误。

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myAppDao': Unsatisfied dependency expressed through method 'setAuditStore' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'myapp.AuditStore' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

AuditStore是一个非常复杂的对象,我不使用这个类功能进行测试(我需要null或模拟这个类)。有什么方法可以避免创建一个在xml中定义的AuditStore的bean并使其工作。

我知道让@Autowired(required = false)生效,会改变应用程序代码进行测试,所以我正在寻找其他选择。

如果有其他选择,请提供帮助。

1 个答案:

答案 0 :(得分:1)

如果可能,您应该考虑转移到注释驱动的配置并使用类似@InjectMock的内容。但是,假设您需要坚持使用问题中列出的方法,则可以通过以下几种方式在MyAppHibernateDao中定义spring-myapp-db-connector-test.xml的模拟实例:

  • Use a factory bean
  • 使用Springockito。当然,
  • myAppDao中声明spring-myapp-db-connector-test.xml bean,如下所示:

    <bean id="myAppDao" class="org.mockito.Mockito" factory-method="mock">
        <constructor-arg value="myapp.MyAppHibernateDao"/>
    </bean>
    

然后,您可以@Autowire MyAppHibernateDao进入MyAppHibernateDaoIntegrationTest并在测试/设置方法中设置预期等。