如何将JUnit测试的结果记录到文件中?

时间:2015-06-16 14:40:15

标签: java junit

之前我从未使用过日志记录机制,但现在我需要将JUnit测试的结果记录到文件中。

我想将以下测试的结果(无论是通过,失败还是抛出异常)记录到日志文件中。

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

有人可以建议如何实现这个目标吗?

来自评论:

我目前正在使用这种记录机制: - ginny singh 22分钟前

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();

1 个答案:

答案 0 :(得分:0)

您可以使用JUnit

中的TestWatcher规则
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");
    }
}