简体   繁体   中英

Log all errors/failures from a list of JUnit tests into a text file

I'm writing a test harness and a set of junit tests to test various HTTP methods on various environments. Currently I have a bunch of tests written, and ultimately what I'd like to do is to be able to output all errors/failures from the Junit tests to a text file. What is the best way to accomplish this?

For example, if a test fails, I'd like to say the name of the junit test, and some information (which would come from the Test Harness class, such as the response status code and the status code description).

Try using Apache Log4J .

Another way is sending the information to a file. Check this tutorial . When your test fails, you can just append() the information to your file.

.append(this.class() + respone.getStatus() + response.getCode());

You should use the TestWatcher detailed on https://github.com/junit-team/junit/wiki/Rules#testwatchmantestwatcher-rules

public class WatchmanTest {
  private static String watchedLog;

  @Rule
  public TestRule watchman = new TestWatcher() {
    @Override
    public Statement apply(Statement base, Description description) {
      return super.apply(base, description);
    }

    @Override
    protected void succeeded(Description description) {
      watchedLog += description.getDisplayName() + " " + "success!\n";
    }

    @Override
    protected void failed(Throwable e, Description description) {
      watchedLog += description.getDisplayName() + " " + e.getClass().getSimpleName() + "\n";
    }

    @Override
    protected void skipped(AssumptionViolatedException e, Description description) {
      watchedLog += description.getDisplayName() + " " + e.getClass().getSimpleName() + "\n";
    }

    @Override
    protected void starting(Description description) {
      super.starting(description);
    }

    @Override
    protected void finished(Description description) {
      super.finished(description);
    }
  };

  @Test
  public void fails() {
    fail();
  }

  @Test
  public void succeeds() {
  }
}

You'll implement the methods and JUnit was give you a callback on your failed() method with the exception which caused the failure and a Description object which holds more information on the test. You shoudl also take a look at the ExternalResource class on that page as it details how you can do a reliable set up and tear down of resources to use in your TestWatcher such as the file you want to write to.

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