views:

44

answers:

1

Hi,

I have an ant build file that contains JUnit test suite that I would like to execute. Currently I just right click and run the build file from Eclipse.

I want to write a java code that can execute the ant build file automatically. So I just run the code and ant will be executed.

Second is I want to capture the test result. Currently the result is based on JUnit HTML report. I want to make my own simple test report. I read there is JUnitResultFormatter but I can't find the instructional step by step how to use it. Can anyone point me the reference?

Thanks in advance.

+2  A: 

The easiest way to do that is to use the JunitCore class from java. It is not advised to call the main from ant directly, see the Junit Faq, and http://www.answerspice.com/c119/1497833/how-do-i-run-junit-tests-from-inside-my-java-application.

It is very common to define a main like this for each test case, to be able to run the tests individually from command line. I usually also change the logging settings in those methods, to get more information when I run a single test manually than from within ant.


In order then to create a custom report, you will have to implement a RunListener that creates your report, and register it, as described in the javadoc:

public void main(String... args) {
  JUnitCore core= new JUnitCore();
  core.addListener(new RingingListener());
  core.run(MyTestClass.class);
}

Your listener will then be called before and after each test run, and passed descriptive information about the test that is about to run, and how the test went once it is done.

tonio
thanks for the detail :)Is it by doing this, it does eliminate the need for ant build file because it specifically call the test class?
Iso
Yes, with this, you will be able to call the tests without `ant`. You can also mix both, and still use ant to automate running all your tests, for example in continuous integration.
tonio
sorry to ask again, but how do I specify the path to the test class if its not in the same folder?These are my folder structure:SampleTest-> build-->test--->classes---->test.diagram1_Suite1.class (this the class file)->test-->RunTest.class (this is the executor)thanks again
Iso
See in the code sample the line `core.run(MyTestClass.class);`. The `JunitCore` loads tests based on class names. You simply have to reference the fully qualified class name of your test, and make sure this class is in the classpath.
tonio
:( the code works fine but I found out that I need to run the ant file and can't use this way to execute my JUnit (because my java code is not in a java project). any idea how to overcome this?
Iso
I'm not sure to understand the problem here. You can run your tests from ant without the junit task if you need to, using the `java` task.
tonio