Utilizing Ant's JUnit functionality using java code instead of ant scripts

I am currently working on an automated testing system and I am attempting to use the Ant functionality from within a MessageDrivenBean.

Specifically I need to emulate the clean, build, batchtest, and junitreport tags. I am aware that it is possible to simply run an existing ant script. However, in this case I will not be able to simply have a script parked in a directory where my bean can get to it so I need to be natively calling the Ant API.

To get to where I am, I simply copied a working ant script  that did what I needed to do into comment. Then I went through line-by-line and found the correct java code to match the xml tags. At present I get a null pointer exception when I attempt to run the clean/build target and I get an exception regarding a TestListener when I try to perform the batchtest operation.

The null pointer exception is a side effect of what paths Weblogic and my bean have acess to while running. That is a matter of finding out what to put where. The significant part is the testing.

I have tried using batchtest in two different ways, both fail in the same manner. The first is to add batch test to a junit task and then run the target. The second is to call a JUnitTestRunner. Both throw a 'missing TestListener' exception. I think my code is correct, I just need to figure out how to attach a TestListener to the batch test OR find out why JUnitTestRunner (which inherits from TestListener) doesnt work. Code follows:

public static void RunTests(String path) {
            try {
                  //            establish a project, akin to just creating the script
                  Project project = new Project();
                  //            <project name="my core" default="default" basedir="../">
                  project.setName("my Test");
                  project.setDefault("Run All Tests");
                  project.setBasedir("../");
                  project.init();

                  //            create a new property (inherits from task)
                  //            Property property = (Property) project.createTask("Run my
                  // Test");
                  //            property.setProject(project);

                  //          <property file="scripts/default.properties"/>
                  //          <property file="scripts/dev_build.properties" />
                  //            property.setFile(new File("scripts/default.properties"));
                  //            property.setFile(new File("scripts/dev_build.properties"));

                  //            <target name="my Tests" depends="Compile CL Tests"
                  //              description="Run my Unit Tests">
                  Target runTarget = new Target();
                  runTarget.setProject(project);
                  runTarget.setName("Run All Tests");
                  runTarget.setDepends("Compile All Tests");

                  //              <junit fork="true" showoutput="yes" haltonfailure="false"
                  // printsummary="withOutAndErr">
                  JUnitTask jUnitTask = new JUnitTask();
                  jUnitTask.setFork(true);
                  jUnitTask.setShowOutput(false);
                  jUnitTask.setHaltonfailure(false);
                  SummaryAttribute summaryAttribute = new SummaryAttribute();
                  summaryAttribute.setValue("true");
                  jUnitTask.setPrintsummary(summaryAttribute);

                  //            <batchtest>
                  //            a batch test to collect and run the tests
                  BatchTest batchTest = jUnitTask.createBatchTest();
                  //            <fileset dir="myprojectdir">
                  //            establish a FileSet from the path argument
                  //            add that fileset to a batchtest
                  FileSet batchTestFileSet = new FileSet();
                  //            <include name="mytestcasepattern"/>
                  //            include all TestCase source...
                  batchTestFileSet.setIncludes("**/*TestCase.java");
                  //            ...from this directory
                  batchTestFileSet.setDir(new File(path));
                  //            </fileset>

                  //            <batchtest todir="myoutputdir">
                  //            add the fileset to the batchtest
                  batchTest.addFileSet(batchTestFileSet);
                  batchTest.setTodir(new File("/tmp"));
                  //            </batchtest>
                  
                  //      <formatter type="xml"/>
                  FormatterElement formatterElement = new FormatterElement();
                  TypeAttribute typeAttribute = new TypeAttribute();
                  typeAttribute.setValue("XML");
                  formatterElement.setType(typeAttribute);
                  jUnitTask.addFormatter(formatterElement);
                  //    </junit>
                  runTarget.addTask(jUnitTask);

                  //    <junitreport todir="${tmp.dir}">
                  //      <fileset dir="${tmp.dir}"
                  //          includes="TEST-*.xml"/>
                  //      <report format="frames"
                  //          todir="${tmp.dir}"/>
                  //  </junitreport>
                  //            </target>
                  project.addTarget(runTarget);

                  //          <target name="Compile my Tests">
                  Target compileTarget = new Target();
                  compileTarget.setName("Compile All Tests");
                  compileTarget.setProject(project);

                  //        <delete>
                  Delete delete = new Delete();
                  //          <fileset dir="mywebapp/WEB-INF/classes/test"
                  // includes="**/*.class"/>
                  FileSet deleteFileSet = new FileSet();
                  deleteFileSet.setDir(new File("**/test"));
                  deleteFileSet.setIncludes("**/*.class");
                  delete.addFileset(deleteFileSet);
                  delete.setQuiet(true);
                  //        </delete>
                  compileTarget.addTask(delete);

                  //        <javac srcdir="mysrc/test" deprecation="on" debug="on">
                  Javac javac = new Javac();
                  Path javacPath = new Path(project);
                  javacPath.setPath("**/test");
                  javac.setSrcdir(javacPath);
                  //            <classpath refid="test.cl.class.path"/>
                  compileTarget.addTask(javac);
                  //    </target>
                  project.addTarget(compileTarget);

                  project.executeTarget("Run All Tests");
            } catch (Exception e) {

            }
      }
}

      public static void RunTests(String path) {
                        
            try {
                  //            establish a project, akin to just creating the script
                  Project project = new Project();
                  //            <project name="my core" default="default" basedir="../">
                  project.setName("my Test");
                  project.setDefault("Run All Tests");
                  project.setBasedir("../cc_wescom_ear/webapp_cl");
                  project.init();
                  logger.log(Level.INFO, "project.init");
                  
//                <target name="Compile myTests">
                  Target compileTarget = new Target();
                  compileTarget.setName("Compile All Tests");
                  compileTarget.setProject(project);

                  //        <delete>
                  Delete delete = new Delete();
                  //          <fileset dir="mywebapp_/WEB-INF/classes/test"
                  // includes="**/*.class"/>
                  FileSet deleteFileSet = new FileSet();
                  deleteFileSet.setDir(new File("**/test"));
                  deleteFileSet.setIncludes("**/*.class");
                  delete.addFileset(deleteFileSet);
                  delete.setQuiet(true);
                  //        </delete>
                  compileTarget.addTask(delete);

                  //        <javac srcdir="mywebapp/test" deprecation="on" debug="on">
                  Javac javac = new Javac();
                  Path javacPath = new Path(project);
                  javacPath.setPath("**/test");
                  javac.setSrcdir(javacPath);
                  //            <classpath refid="test.class.path"/>
                  compileTarget.addTask(javac);
                  //    </target>
                  project.addTarget(compileTarget);
                  

                  logger.log(Level.INFO, "start compile test");
                  project.executeTarget("Compile All Tests");
                  logger.log(Level.INFO, "end compile test");

                  logger.log(Level.INFO, "start batch test");
                  BatchTest batchTest = new BatchTest(project);
                  FileSet batchTestFileSet = new FileSet();
                  batchTestFileSet.setIncludes("**/*TestCase.java");
                  batchTestFileSet.setDir(new File(path));
                  batchTest.addFileSet(batchTestFileSet);
                  batchTest.setTodir(new File("/tmp"));      
                  logger.log(Level.INFO, "end batch test");
                  
                  logger.log(Level.INFO, "start enum batch test");
                  Enumeration en = batchTest.elements();
                  while(en.hasMoreElements())
                  {
                        new JUnitTestRunner((JUnitTest)((BaseTest) en.nextElement()), false, false, false, false);
                  }
                  logger.log(Level.INFO, "end enum batch test");
                  
            } catch (Exception e) {
                  logger.log(Level.WARNING, e.toString());
            }
      }
}

It seems that it is entirely possible to use the Ant API in this manner, though from searches here and the internet-at-large it is certainly not common. Before anyone asks, simply running the scripts is ABSOLUTELY NOT an option.
mloakleyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CEHJCommented:
Can't really offer much here apart from the unappealing notion of testing (where possible) that paths result in readable entities in the container in each case
mloakleyAuthor Commented:
Is there an alternative method to run the tests and get some sort of report format?

I had also considered using the JUnit API, however it is poorly documented and targeted at JUnits own graphical test runner rather than a behind-the-scenes automated test.
CEHJCommented:
>> Is there an alternative method to run the tests and get some sort of report format?

Not sure - unfortunately don't use JUnit
Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

mloakleyAuthor Commented:
Upped point value. I'm keen to get this working so that I don't lose 3 hours of my day babysitting scripts. Running scripts is still not an option, this has to be done in proper java code.

If anyone actually knows anything about running JUnit or Ant programatically instead of via a GUI test runner/IDE plugin or a script, respectively, any links, documents, articles would be useful.

The closest reference I have found is at: http://www.ftponline.com/javapro/2004_06/magazine/features/kgauthier/default.aspx
mloakleyAuthor Commented:
Solved it myself.

Ant was the wrong way to go. Its a really useful tool as an XML script, but the API was never intended to be used directly.

I ended up using standard Java File I/O and regex pattern matching to find my tests.

To run them I used a TestRunner, TestResult, and Test from JUnit to load, run, and get the results from those tests.
GhostModCommented:
PAQed with points refunded (500)

GhostMod
Community Support Moderator

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.