Search code examples
javajunitant

Ant build Junit test Autowire fails


The junits configured in project works fine when I run them within eclipse individually but when I run the Ant build with junit goal the test classes gets executed but throws NPE for the autowired components. I have specified below context configuration which should take care of finding the context and autowiring the beans from it.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:DaoContextTest.xml" })

My ant build junit goal looks as below:

<target name="junit" depends="build">
  <junit printsummary="yes" haltonfailure="yes">
    
    <classpath refid="classpath-test" />
    <classpath location="${webclasses.dir}" />
        
     <formatter type="plain" usefile="false"/>
    <batchtest fork="yes" todir="${test.classes}">
        <fileset dir="${src.dir}">
            <include name="**/*Test.java" />
        </fileset>
    </batchtest>
  </junit>
</target>

I verified the classpath in ant debug mode and it has the right location of this xml file. I suppose if the xml was missing it would have complained failed to load context and if my DaoContext xml had incorrect bean configuration then my junit wouldnt have run when I run it manually so I suspect it must be something specific to Ant.

And the exception I get is NPE on the autowired components. I am using ant 1.9.6, I tried copying the ant-junit.1.9 jar to the web-inf lib but that did not help. Much appreciated if anyone can please point me in the right direction? I found similiar post here but it is still open.


Solution

  • Solution was this and this.

    In brief: Ant is using Junit3 test runner by default so to enforce Junit4 runner need to include below method in each of the Junit classes.

     public static junit.framework.Test suite() {
            return new JUnit4TestAdapter(MyJunitTest.class);
        }