簡體   English   中英

將自定義消息添加到JUnit4樣式異常測試

[英]Adding Custom Messages to JUnit4 Style Exception Tests

我有以下測試:

@Test(expected=ArithmeticException.class) 
   public void divideByZero() {
   int n = 2 / 1;
}

這里所見。

我想添加一條消息,該消息將在測試失敗時顯示。

例如,如果我正在進行斷言測試,則可以執行以下操作來添加一條消息:

@Test public void assertFail(){
    Assert.fail("This is the error message I want printed.");
    Assert.assertEquals(true, false);
}

第二個示例應打印出“這是我要打印的錯誤消息。”。 如何設置第一個示例消息文本?

也許@Rule注釋應該有所幫助。 在您的單元測試課中添加如下內容:

import org.junit.Rule;
import org.junit.rules.MethodRule;
import org.junit.runners.model.Statement;
import org.junit.runners.model.FrameworkMethod;
import org.junit.internal.runners.model.MultipleFailureException;
...
@Rule
public MethodRule failureHandler = new MethodRule()
{
    @Override
    public Statement apply(final Statement base, FrameworkMethod method, Object target)
    {
        return new Statement()
        {
            @Override
            public void evaluate() throws Throwable
            {
                List<Throwable> listErrors = new ArrayList<Throwable>();
                try
                {
                    // Let's execute whatever test runner likes to do
                    base.evaluate();
                }
                catch (Throwable testException)
                {
                    // Your test has failed. Store the test case exception
                    listErrors.add(testException);                        
                    // Now do whatever you need, like adding your message,
                    // capture a screenshot, etc.,
                    // but make sure no exception gets out of there -
                    // catch it and add to listErrors
                }
                if (listErrors.isEmpty())
                {
                    return;
                }
                if (listErrors.size() == 1)
                {
                    throw listErrors.get(0);
                }
                throw new MultipleFailureException(listErrors);
            }
        };
    }
};

除了收集listErrors所有異常之外,您可以考慮將testException與帶有附加消息的異常包裝testException ,然后將其拋出。

如果您願意使用catch-exception而不是JUnit的內置異常處理機制,那么可以輕松解決您的問題:

catchException(myObj).doSomethingExceptional();
assertTrue("This is the error message I want printed.",
           caughtException() instanceof ArithmeticException);

我不認為您可以輕松地做到這一點 ,但是這個人似乎已經在解決這個問題上做了部分努力。

我建議改為命名測試,以使測試顯而易見,從而使某些測試失敗時,它們會告訴您問題出在哪里。 這是使用ExpectedException規則的示例:

@RunWith(JUnit4.class)
public class CalculatorTest {
  @Rule
  public ExpectedException exception = ExpectedException.none();

  @Test
  public void divisionByZeroShouldThrowArithmeticException() {
    Calculator calculator = new Calculator();

    exception.expect(ArithmeticException.class);
    calculator.divide(10, 0);
  }
}

有關ExpectedException詳細信息,請參閱本文ExpectedException JavaDoc。

暫無
暫無

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

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