Friday, July 11, 2014

Apache Ant vs Gradle : JUnit

Suppose you had the following test case:
import org.junit.Test;

import static org.junit.Assert.assertThat;
import static org.hamcrest.core.Is.is;

import org.junit.runner.JUnitCore;

public class TestHelloWorld {

 @Test
 public void testAPassingTest() {
  assertThat(true, is(true));
 }

 @Test
 public void testAFailingTest() {
  assertThat(true, is(false));
 }
}
To compile this from the command line you would type
javac -cp junit-4.11.jar;hamcrest-core-1.3.jar
  TestHelloWorld.java
And then to run it you would do:
java -cp .;junit-4.11.jar;hamcrest-core-1.3.jar
  org.junit.runner.JUnitCore TestHelloWorld
Here's how that would look in Apache Ant:
<?xml version="1.0"?>
<project>
   <path id = "classPath">
      <pathelement location = "junit-4.11.jar" />
      <pathelement location = "hamcrest-core-1.3.jar" />
   </path> 

   <javac srcdir = "." includes = "TestHelloWorld.java" includeAntRuntime = "false"
      classpathref = "classPath" />

   <junit fork = "true">
      <classpath refid = "classPath" />
      <formatter type="plain" usefile = "false" />
      <test name = "TestHelloWorld" />
   </junit>
</project>
Note: If you forget to set the fork attribute to true, you'll get an error message similar to the following.
Buildfile: C:\newFolder\build.xml
    [junit] Testsuite: TestHelloWorld
    [junit] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0,
              Time elapsed: 0.03 sec
    [junit]
    [junit] Testcase: initializationError took 0 sec
    [junit]     Caused an ERROR
    [junit] No runnable methods
    [junit] java.lang.Exception: No runnable methods
    [junit]     at java.lang.reflect.Constructor
                  .newInstance(Constructor.java:525)
    [junit]
    [junit] Test TestHelloWorld FAILED

BUILD SUCCESSFUL
Total time: 0 seconds
Likewise, if you forget to set the formatter's usefile attribute to false the test results will be written to a file (ex. TEST-TestHelloWorld.txt) instead of being displayed on the console.

Gradle expects Java tests in the directory src/test/java. Here's what the build script would look like:
apply plugin: 'java'

repositories {
 mavenLocal()
 mavenCentral()
}

dependencies {
 testCompile 'junit:junit:4.11'
}
To run this specific test from the command line, you would do:
gradle test --tests TestHelloWorld

References

 

No comments:

Post a Comment