JUnit Rule not being executed when test fails

2019-07-29 17:24发布

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?

标签: junit-rule
1条回答
家丑人穷心不美
2楼-- · 2019-07-29 18:10

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>
查看更多
登录 后发表回答