1
我正在使用junit來測試我的一些服務。我使用spring來注入服務以及所有依賴項。我的測試課程看起來像下面這樣。junit配置文件中的bean定義
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/location/MyServiceTest-context.xml"})
@Transactional
public class MyServiceTest extends TestSupport {
@Autowired
private MyService myService;
@Test
public void testX() throws Exception {
...
}
}
配置文件是:
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="entityBasePackages" class="java.lang.String">
<constructor-arg value="com.package1.model"/>
</bean>
<bean id="bean1" class="org.easymock.EasyMock" factory-method="createMock">
<constructor-arg value="com.package2.bean1"/>
</bean>
<bean id="bean2" class="org.easymock.EasyMock" factory-method="createMock">
<constructor-arg value="com.package3.bean2"/>
</bean>
<context:component-scan base-package="com.package4.MyService"/>
</beans>
爲MyService使用bean1。 bean1依賴於bean2,也就是它使用它。當我像這樣運行我的測試時,它工作正常。但是,如果我在配置XML聲明bean2以上bean1,測試失敗了
org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.package2.bean1]
我猜Spring讀取文件,當它到達一個bean定義,試圖電線它 - 這就是爲什麼它的崩潰我的情況。有沒有辦法告訴Spring閱讀整個文件,然後嘗試連接bean?這樣我就可以編寫我的bean定義而不用擔心它們的順序。謝謝
順序應該沒關係! Spring不會立即嘗試連接,它會根據可用配置(bean定義)創建元數據,然後開始將bean連接在一起。你說bean1依賴於bean2,但這裏都似乎是嘲弄的嗎?你可以展示一下你將Mock連接在一起的配置 –