1
votes

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.

1
How is the eventFeed object created in the unit test? And why don't you use a classpath resource in your test rather than a relative file resource? - JB Nizet
How does eventFeed get initialized in the test? How does eventFeed create an AbstractEventParser given that it is abstract? Perhaps you should annotate eventFeed with Autowired and ensure that the subclass of AbstractEventParser that it uses is also Spring-managed, i.e. annotated with Component, Service etc. - Kkkev
All, The eventFeed object is returned by a DAO that I autowire (successfully) into the test. Kkkev, where do you suggest I add an @autowired annotation to eventFeed? In the JUnit test? - Dave

1 Answers

0
votes

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