问题
Following is my test file :
package test;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
public class TestWatcherTest
{
@Rule
public TestWatcher testWatcher = new TestWatcher()
{
protected void failed(Throwable e, Description description)
{
System.out.println("in failed()");
}
};
@Test
public void shouldFail()
{
Assert.assertTrue("Test failed", false);
}
}
Output is :
<failure message="Test failed" type="junit.framework.AssertionFailedError">junit.framework.AssertionFailedError: Test failed at test.TestWatcherTest.shouldFail(TestWatcherTest.java:24)
</failure>
It seems failed() is not being executed. I read many posts but nothing seems to work for me. What am I doing wrong?
回答1:
The issue was with ant configuration. From http://testautomationusingjunit.blogspot.com/2013/08/applying-rules-to-junit-tests-running.html, the target needs to be edited to contain JUnitCore in the classpath.
<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>
来源:https://stackoverflow.com/questions/18364859/junit-rule-not-being-executed-when-test-fails