我有一個dao類,它依賴於另一個實用程序類AuditStore
。引起:org.springframework.beans.factory.UnsatisfiedDependencyException:創建名爲'myAppDao'的bean時出錯:
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>
WHE我運行此我得到以下錯誤。
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)
會工作,這將改變測試的應用程序代碼,所以我正在尋找其他選項。
如果有其他選擇,請幫助。
你已經回答了你自己的問題...使用模擬。 –
如何在xml中定義類AuditStore的這個模擬對象? – Edayan