3

I never used a logging mechanism before, but now I have requirement to log the results of my JUnit tests to a file.

I want to log the result of below test (whether pass, fail or throw exception) to a log file.

@Test
public void statusCode200() {
    Assert.assertEquals("Java class".getStatusCode(), 200);
}

Can someone please advise how to achieve this?


From the comments:

I am currently using this logging mechanism: – ginny singh 22 mins ago

fileHandler = new FileHandler(System.getProperty("user.dir")+"//ExecutionResults.log");
simpleFormatter = new SimpleFormatter(); 
StreamHandler sh = new StreamHandler(System.out, simpleFormatter); 
log.setUseParentHandlers(false); 
log.addHandler(sh);   
log.addHandler(fileHandler); 
fileHandler.setFormatter(simpleFormatter); 
fileHandler.setLevel(Level.ALL); 
log.setLevel(Level.ALL); 
log.config("Logger Configuration done."); 
fileHandler.close();
Stefan Birkner
  • 24,059
  • 12
  • 57
  • 72
ginny singh
  • 31
  • 1
  • 3

1 Answers1

0

You can use TestWatcher rule from the JUnit library

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

import java.io.IOException;
import java.io.PrintWriter;

public class LogJunitTests {
    private static StringBuilder builder = new StringBuilder();
    @AfterClass
    public static void afterClass() throws IOException {
        PrintWriter logFile = new PrintWriter("You Log Path", "UTF-8");
        logFile.write(builder.toString());
        logFile.close();
    }

    @Rule
    public TestWatcher watchman = new TestWatcher() {

        @Override
        protected void failed(Throwable e, Description description) {
            if (description != null) {
                builder.append(description);
            }
            if (e != null) {
                builder.append(' ');
                builder.append(e);
            }
            builder.append(" FAIL\n");
        }

        @Override
        protected void succeeded(Description description) {
            if (description != null) {
                builder.append(description);
            }
            builder.append(" OK\n");
        }
    };

    @Test
    public void test() {
        Assert.assertEquals("Java class", "Java class");
    }
}
Daniel Taub
  • 5,133
  • 7
  • 42
  • 72