簡體   English   中英

Java:在JUnit中使用記錄器斷言*

[英]Java: using a logger in JUnit assert*

我想要做的是像JUnit中的以下內容:

assertTrue(logger.error("the condition is not true"), <a boolean condition>);

所以記錄器記錄錯誤消息,記錄器可以是例如commons或log4j。

但Junit斷言不接受記錄器參數,所以有沒有辦法實現這一點,或者我是否需要嘗試捕獲斷言並在catch塊中記錄錯誤消息?

您可以使用JUnit TestRule TestWatcher TestRule在測試方法之前和之后執行代碼(類似於@Before@After ),但是您可以訪問更多信息,更重要的是,可以訪問測試結果。 TestWatcher定義了successeded succeeded()failed()starting()finished()等方法,您可以實現這些方法以獲取事件通知。

以下示例僅使用失敗的斷言打印出失敗的測試。

public class TestWatcherTest {
  @Rule
  public TestWatcher testWatcher = new TestWatcher() {
    protected void failed(Throwable e, Description description) {
      System.out.println("" + description.getDisplayName() + " failed " + e.getMessage());
      super.failed(e, description);
    }

  };

  @Test
  public void test1() {
    Assert.assertEquals("hello world", 3, 4);
  }
}

你可以顯然做你喜歡的而不是System.out.println()。 這產生了輸出:

test1(uk.co.farwell.junit.TestWatcherTest) failed hello world expected:<3> but was:<4>

請注意,失敗的斷言是一個例外,因此您可以訪問堆棧跟蹤等。

我不會改變或擴展JUnit類。

您嘗試/捕獲和記錄錯誤的安排將是更可取的。

問題是Assert失敗不一定是個例外。

感覺就像你正在嘗試將log4j變成已經存在的報告功能。 我建議您查看Ant JUnit報告任務 - 它會給你一個漂亮的報告,它比日志更有用。

更新:

您始終可以添加另一個log4j文件追加器。 讓log4j將消息寫入控制台和您選擇的文件。 如果我是正確的,你的代碼根本沒有變化。

那么更好地使用它

if(!<condition>) {
logger.error("my message");
Assert.fail();
}

暫無
暫無

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

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