簡體   English   中英

如何將JUnit測試的結果記錄到文件中?

[英]How to log results of JUnit test to a file?

我之前從未使用過日志記錄機制,但現在我需要將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();

您可以使用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");
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM