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;

import org.junit.runner.JUnitCore;

public class TestHelloWorld {

 public void testAPassingTest() {
  assertThat(true, is(true));

 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
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"?>
   <path id = "classPath">
      <pathelement location = "junit-4.11.jar" />
      <pathelement location = "hamcrest-core-1.3.jar" />

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

   <junit fork = "true">
      <classpath refid = "classPath" />
      <formatter type="plain" usefile = "false" />
      <test name = "TestHelloWorld" />
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] 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
    [junit] Test TestHelloWorld FAILED

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 {

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



No comments:

Post a Comment