1

I'm using Spring 3.1.0.RELEASE and JUnit 4.8.1. I'm having trouble figuring out why a class' member field isn't getting autowired in a JUnit test. My test looks like ...

@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
}

The class "EventFeed" invokes an instance of the below class ...

package com.myco.myproject.parsers;
...
public abstract class AbstractEventParser {

    @Autowired
    protected NetUtilsService netUtilsService;
    ...
}

but when it comes time, the AbstractEventParser's "netUtilsService" member field is null. This is strange because in my "testApplicationContext.xml" file, I have this, which I thought would take care of the autowiring ...

<mvc:annotation-driven />
<context:component-scan base-package="com.myco.myproject" />

How do I force autowiring in my JUnit test? I would prefer not to add and invoke a setter method for the member field but if that is the only way, so be it.

4

1 回答 1

0

EventFeed由 Spring 管理的类,我的意思是 EventFeed 类用@Serviceor注释@Component。你也需要在你的测试中做对@AutowiredEventFeed我在你的身上没有看到AbstractParsetTest

于 2012-05-11T19:14:51.877 回答