There are quite a lot of really excellent posts on how to apply a Rule to a JUnit Test. But unfortunately, nowhere has it specified how to run the tests using ant. Rather, how to edit ant build.xml to include junit.jar (I use selenium-server.jar) in the classpath. After long hours of googling, I figured out the following.
Between, to run tests without using ant, see Run JUnit tests from terminal using selenium.jar
To run tests using ant, I hope you have ant configured on your machine. If you are using ant with junit.jar, as they say, {Copied from http://ant.apache.org/manual/Tasks/junit.html}
Note: You must have
Between, to run tests without using ant, see Run JUnit tests from terminal using selenium.jar
To run tests using ant, I hope you have ant configured on your machine. If you are using ant with junit.jar, as they say, {Copied from http://ant.apache.org/manual/Tasks/junit.html}
Note: You must have
junit.jar
available. You can do one of:- Put both
junit.jar
andant-junit.jar
inANT_HOME/lib
. - Do not put either in
ANT_HOME/lib
, and instead include their locations in yourCLASSPATH
environment variable. - Add both JARs to your classpath using
-lib
. - Specify the locations of both JARs using a
<classpath>
element in a<taskdef>
in the build file. - Leave
ant-junit.jar
in its default location inANT_HOME/lib
but includejunit.jar
in the<classpath>
passed to<junit>
. (since Ant 1.7)
In my project, I use ant with selenium-server.jar. Selenium server contains junit, so it's not required to include junit explicitly in the classpath. Okay, so now, in the build file, edit your target to contain following elements:
<target name="junit" depends="build">
<java classname="org.junit.runner.JUnitCore">
<classpath>
<path location="selenium_server/selenium-server-standalone-xxx.xx.jar"/>
</classpath>
</java>
<junit fork="no" haltonfailure="no" printsummary="true" failureProperty="test.failed" dir=".">
<test name="src.SampleTest" todir="./report" />
</junit>
</target>
Now, if you need to see how to write a simple test using Rule,
package src;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import static org.junit.Assert.assertTrue;
public class SampleTest {
@Rule
public OpenBrowserOnFailure onFailure = new OpenBrowserOnFailure();
@Test
public void shouldFail() {
assertTrue(false);
}
}
class OpenBrowserOnFailure extends TestWatcher {
public OpenBrowserOnFailure() {
System.out.println("in constructor");
}
@Override
protected void failed(Throwable e, Description description) {
System.out.println("Only executed when a test fails");
}
}
and the output will be:
in constructor
Only executed when a test fails
and the output will be:
in constructor
Only executed when a test fails