2017-09-05 86 views
0

我有一個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)會工作,這將改變測試的應用程序代碼,所以我正在尋找其他選項。

如果有其他選擇,請幫助。

+0

你已經回答了你自己的問題...使用模擬。 –

+0

如何在xml中定義類AuditStore的這個模擬對象? – Edayan

回答

1

如果可能,你應該考慮轉向註解驅動的配置,並使用類似@InjectMock的東西。但是,假設你必須堅持你在你的問題中列出的方法,你可以通過多種方式定義在spring-myapp-db-connector-test.xmlMyAppHibernateDao一個模擬實例:

  • Use a factory bean
  • 使用Springockito。而且,當然,
  • spring-myapp-db-connector-test.xml聲明myAppDao豆如下:

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

然後,您可以@Autowire MyAppHibernateDaoMyAppHibernateDaoIntegrationTest,並設置在測試/設置方法就可以了預期等。

+0

這個想法是模擬AuditStore而不是MyAppHibernateDao,但是這種方法很有效,非常感謝。 – Edayan

相關問題