繁体   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