我使用的是Spring 3.1.0.RELEASE和JUnit 4.8.1。我無法弄清楚爲什麼類的成員字段沒有在JUnit測試中自動裝配。我的測試看起來像......如何在JUnit測試中強制自動裝配?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "file:src/test/resources/testApplicationContext.xml" })
@TransactionConfiguration(defaultRollback=true)
@Transactional
public abstract class NowYouKnowEventsParserTest {
private EventFeed eventFeed;
@Before
public void setUp() {
eventFeed = getEventFeed(16);
} // setUp
@Test
public void testParser() {
Assert.assertNotSame(0, eventFeed.getEvents().size());
} // testParser
...
@Autowired
private EventFeedsDao eventFeedsDao;
protected EventFeed getEventFeed(final Integer id) {
return eventFeedsDao.findById(id);
} // getEventFeed
}
類「EventFeed」調用下面的類的實例...
package com.myco.myproject.parsers;
...
public abstract class AbstractEventParser {
@Autowired
protected NetUtilsService netUtilsService;
...
}
但說到時,AbstractEventParser的「netUtilsService」成員場空值。這很奇怪,因爲在我的「testApplicationContext.xml」的文件,我有這個,我認爲會照顧自動裝配...
<mvc:annotation-driven />
<context:component-scan base-package="com.myco.myproject" />
如何強制在我的JUnit測試自動裝配?我不想爲成員字段添加和調用setter方法,但如果這是唯一的方法,那就這樣做吧。
中沒有看到如何在單元測試中創建eventFeed對象?爲什麼不在測試中使用類路徑資源而不是相對文件資源? –
eventfeed如何在測試中初始化? eventFeed如果創建一個AbstractEventParser,它是抽象的嗎?也許你應該使用Autowired註釋eventFeed,並確保它使用的AbstractEventParser的子類也是Spring管理的,即使用Component,Service等進行註釋。 – Kkkev
All,eventFeed對象由我自動裝入(成功)的DAO返回到測試。 Kkkev,你在哪裏建議我給eventFeed添加一個@autowired註解?在JUnit測試中? – Dave