我收到錯誤,試圖將資源依賴項注入到我的單元測試中。 我的方法是編寫一個TestConfig.java來替換用於管理bean連接的生產的applicationContext.xml。這樣我就可以使用內存數據庫運行它,只需測試組件。@Autowired bean not found
TestConfig.java
@Configuration
@EnableTransactionManagement
public class TestConfig {
@Bean
public DataSource dataSource() {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.hsqldb.jdbcDriver");
ds.setUrl("jdbc:hsqldb:mem:testdb");
ds.setUsername("sa");
ds.setPassword("");
return ds;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(){
LocalContainerEntityManagerFactoryBean lcemfb
= new LocalContainerEntityManagerFactoryBean();
lcemfb.setDataSource(this.dataSource());
lcemfb.setPackagesToScan(new String[] {"com.dao","com.data"});
lcemfb.setPersistenceUnitName("MyTestPU");
HibernateJpaVendorAdapter va = new HibernateJpaVendorAdapter();
lcemfb.setJpaVendorAdapter(va);
Properties ps = new Properties();
ps.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
ps.put("hibernate.hbm2ddl.auto", "create");
lcemfb.setJpaProperties(ps);
lcemfb.afterPropertiesSet();
return lcemfb;
}
@Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager tm = new JpaTransactionManager();
tm.setEntityManagerFactory(this.entityManagerFactoryBean().getObject());
return tm;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
}
@Bean
public AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor()
{
return new AutowiredAnnotationBeanPostProcessor();
}
}
ProductsDaoTest.java
@ContextConfiguration(classes = { TestConfig.class })
@RunWith(SpringJUnit4ClassRunner.class)
public class ProductsDaoTest {
@Resource(name="com.dao.ProductsDao")
private ProductsDao testDao;
@Test
public void testSaveProduct() {
Product productA = new Product();
testDao.save(productA);
Set<Product> products = testDao.getAllProducts();
assertNotNull(products);
}
}
錯誤是錯誤名爲 'com.dao.ProductsDaoTest' 創建豆:資源依賴注射失敗
所以它無法找到ProductDao Bean,它是@Repository和@Autowired sessionFactory。
所以我的猜測是,因爲我沒有使用xml命名這個bean,它找不到它,儘管我認爲它應該自動從setPackagesToScan()中選取它。那麼有沒有辦法手動插入Bean映射,以便可以找到它?
另外更普遍的是這是一個合理的方式去測試Spring DAO配置?
問候, 伊恩
你確定LocalContainerEntityManagerFactoryBean被正確初始化嗎?如果你在entityManagerFactoryBean中放置了一個斷點,你打了嗎?我認爲Spring沒有辦法知道要初始化哪個bean來初始化ProductsDao。 – 2013-02-12 19:02:12
聲明context-component-scan在哪裏?我沒有看到它在測試或我錯過了什麼..請注意,由休眠掃描的包不是一樣的事情春天 – 2013-02-12 19:12:32