简体   繁体   中英

How do I force autowiring in a JUnit test?

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.

Is the EventFeed class managed by Spring, i mean is the EventFeed class annotated with either @Service or @Component . Also you need to do @Autowired of EventFeed in your test right. I am not seeing that in your AbstractParsetTest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM