简体   繁体   中英

Run a method if test fails on Junit

I have added a method to my Selenium framework that takes a screenshot at the end of a test, but as some tests don't run all the way to the end due to failing. i'd like to implement a rule to run this screenshot method if the test fails.

Something like:

@Rule
public Failure fail = new Failure();

if (fail)
{
    // Method
}

You can possibly use TestWatcher this one have hooks for failed and success results. And you can add your hooks logic

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;

public class Test1 {

    @Rule
    public TestWatcher watchman = new TestWatcher() {
        @Override
        protected void failed(Throwable e, Description description) {
            System.out.println("failed");
        }
    };

    @Test
    public void test() {
        Assert.assertEquals(2, 4);
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM