我想在我的Spring MVC應用程序中引入JUnit,並且我正在使用Java和xml配置(我的java配置使用xml來自動裝入某個變量)的組合來定義我的bean:嵌套的Java和Xml的JUnit彈簧配置
// 1 - 我的測試類
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MvcConfiguration_Test.class)
@WebAppConfiguration
public class ClassTest {
@Autowired
@Qualifier("databaseTest")
DataBaseConn conn;
@Test
public void test() {
// do some stuff
}
}
// 2 - 爪哇配置
@EnableWebMvc
@Configuration
@ImportResource({ "applicationContext.xml" }) // this file is in classpath, actually I'm using "classpath:**/applicationContext.xml" but the next step is to move this file in resources/test :)
public class MvcConfiguration_Test extends MvcConf{
@Autowired
String dbName; // defined in applicationContext.xml
@Bean
public DataBaseConn databaseTest(){
DataBaseConn conn = new DataBaseConn();
conn.addDataSource(dbName, jndi, user, pwd)
return conn;
}
}
// 3 - xml配置 - applicationContext.xml中
<?xml version="1.0" encoding="UTF-8"?>
<beans ...
<context:annotation-config />
<bean id="dbName" class="java.lang.String">
<constructor-arg value="myDb"/>
</bean>
</beans>
當我啓動我的JUnit測試,我得到以下錯誤:
java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConfiguration_Test': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: java.lang.String package.MvcConfiguration_Test.dbName; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.String] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
的解決方法是絲骯髒的方式分貝的名字: 字符串DBNAME =「MYDB」; 但這不是所需的解決方案:)
PS。我的MVC應用程序被自動裝配值correclty(我只從MvcConfiguration刪除@ComponentScan("ct.cbi")
讀取測試配置
自動裝配字符串bean對我來說似乎很奇怪。我覺得從屬性文件中讀取這個值是更好的方法。這當然不是我以前見過的。 – Plog